Instant ebooks textbook Clean Code with C# - Second Edition: Refactor your legacy C# code base and improve application performance using best practices Alls download all chapters
Instant ebooks textbook Clean Code with C# - Second Edition: Refactor your legacy C# code base and improve application performance using best practices Alls download all chapters
com
https://textbookfull.com/product/clean-c-sustainable-software-
development-patterns-and-best-practices-with-c-17-1st-edition-stephan-
roth/
textbookfull.com
https://textbookfull.com/product/beautiful-c-30-core-guidelines-for-
writing-clean-safe-and-fast-code-1st-edition-davidson/
textbookfull.com
https://textbookfull.com/product/postcolonial-paris-fictions-of-
intimacy-in-the-city-of-light-laila-amine/
textbookfull.com
Practical Decision Making using Super Decisions v3 An
Introduction to the Analytic Hierarchy Process 1st Edition
Enrique Mu
https://textbookfull.com/product/practical-decision-making-using-
super-decisions-v3-an-introduction-to-the-analytic-hierarchy-
process-1st-edition-enrique-mu/
textbookfull.com
https://textbookfull.com/product/practical-numerical-c-programming-
finance-engineering-and-physics-applications-philip-joyce/
textbookfull.com
https://textbookfull.com/product/a-course-for-teaching-english-
learners-3rd-edition-diaz-rico/
textbookfull.com
https://textbookfull.com/product/language-and-online-identities-the-
undercover-policing-of-internet-sexual-crime-tim-grant-nicci-macleod/
textbookfull.com
https://textbookfull.com/product/urban-experience-and-design-
contemporary-perspectives-on-improving-the-public-realm-1st-edition-
ann-sussman/
textbookfull.com
Testing Software and Systems 32nd IFIP WG 6 1
International Conference ICTSS 2020 Naples Italy December
9 11 2020 Proceedings Valentina Casola
https://textbookfull.com/product/testing-software-and-systems-32nd-
ifip-wg-6-1-international-conference-ictss-2020-naples-italy-
december-9-11-2020-proceedings-valentina-casola/
textbookfull.com
2ND EDITION
JASON ALLS
• Identify low-quality C# code in need of refactoring
• Improve code performance using profiling and refactoring tools
packt.link/free-ebook/9781837635191
• Create efficient and bug-free code using functional
programming techniques
• Write cross-platform code using MAUI
• Develop cloud-deployable microservices for versatile applications
www.packtpub.com
JASON ALLS
Clean Code with C#
Jason Alls
BIRMINGHAM—MUMBAI
Clean Code with C#
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the case
of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the author, nor Packt Publishing 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.
ISBN 978-1-83763-519-1
www.packtpub.com
To my parents, for supporting me throughout my life and career. To all the people in the world of software
that have made my career possible, and who have employed me, trained me, and worked alongside me.
You have been instrumental in helping me to get to where I am today.
I thank you all.
– Jason Alls
Contributors
I would like to thank my parents for always being there, and supporting me throughout my life and
career. Career-wise, I would like to thank all the people in the world of computing who have made my
career possible. Especially those who have employed me, trained me, and worked alongside me. You
have helped me to get to where I am today.
A special thank you to all the staff at Packt Publishing who provided me with the opportunity to write
this book, and who assisted me in improving the content. It has been an eye-opening experience and
a pleasant one. It is your hard work and dedication to the book-writing process that enables computer
programmers like me to become accomplished authors. This book would not be what it is without your
valuable input.
About the reviewers
Vladica Ognjanovic, CEO of MVP-Soft based in the USA and Serbia, holds a Bachelor’s in Computer
Science from the University of Niš. With over two decades in the tech industry, Vladica has mastered
IT management, software development, and database design. He’s led various enterprise projects,
including custom ERP solutions, price tracking systems, IoT solutions, demonstrating strong skills
in web, desktop, and database technologies. Known for innovative problem-solving, Vladica excels
in team leadership and client engagement, making significant contributions to software development
and project management.
Omprakash Pandey, has been working with industry experts and helping SW consultants from
last 20 years. His SW expertise ranges from Microsoft 365, Power Platform, Security Solutions,
JEE technologies, .Net and Cloud expertise. He has been working on areas of Azure Infrastructure,
Azure Development using C#, Azure Architecting. He has also delivered consulting assignments and
developed products for SharePoint custom solutions using .Net. Organizing resources and ensuring
project completion in right time DevOps has been the key transformation agent for the same. He is
also expert in Azure DevOps solution.
Since it first computer, a Commodore Vic20, Gian Maria was interested in everything regarding
Computer Programming. Its passion range from low level (Assembly) to project management. He
worked with Microsoft .NET technologies since very first beta as a passionate Visual Basic .NET then
C# software architect/developer. He has strong experience in DevOps methodologies and techniques,
covering all aspect from managing Requirements to effectively manage code with Git to automatic
Deployment on premise and on cloud resources. Always curious about new technologies he lives and
work in Italy as an independent consultant.
Jegadeesan Ponnusamy worked in the software industry for more than 16 years. He has a master’s
degree in software engineering from the Birla Institute of Technology & Science, Pilani. He received
gold medal, Sri Hiren D. Barucha Memorial award for his excellence in academic and other recognitions
for his work in his career. He currently lives in Voorhees, New Jersey with his wife and two daughters.
Table of Contents
Prefacexvii
1
Coding Standards and Principles in C# 1
Technical requirements 2 Coding principles 5
Good code versus bad code 2 Coding methodologies 10
2
Code Review – Process and Importance 25
A brief introduction to GitHub 26 The company’s coding guidelines and
What is GitHub? 26 business requirement(s) 43
GitHub’s use within the code review process 27 Naming conventions 43
Resources for learning 28 Formatting43
Testing44
The code review process 29 Documentation45
Preparing code for review 30 Architectural guidelines and design patterns 45
Leading a code review 32 Performance and security 47
Issuing a pull request 33 Knowing when to send code for review47
Responding to a pull request 37
Providing and responding to review
Effects of feedback on reviewees 40
feedback48
Knowing what to review 42 Providing feedback as a reviewer 49
viii Table of Contents
3
Classes, Objects, and Data Structures 53
Technical requirements 54 Immutable objects and data structures 85
Organizing classes 54 Using records to create immutable objects 87
A class should have only one Objects should hide data and expose
responsibility58 methods88
Class organization 60 An example of encapsulation 88
Commenting for documentation Data structures should expose data
generation61 and have no methods 89
Cohesion and coupling 65 The SOLID software methodology 90
Tight coupling 66
SRP90
Low coupling 67
Open/closed principle (OCP) 91
Low cohesion 68
Liskov substitution principle (LSP) 91
High cohesion 70
Interface segregation principle (ISP) 93
Designing for change 71 Dependency inversion principle (DIP) 94
Interface-oriented programming 71 Summary95
Dependency injection and inversion of control 74
Questions96
The Law of Demeter 81 Further reading 96
A good and a bad example (chaining) of the
Law of Demeter 83
4
Writing Clean Functions 97
Technical requirements 98 Unclean methods and how they affect
Understanding the difference software102
between OOP and FP 98 FP and clean methods 104
Explanation of the differences 99 FP examples 105
Understanding why FP can lead to cleaner Keeping methods small 109
functions101
Indenting code 112
Table of Contents ix
Breaking out of loops 113 Declaring variables close to their usage 126
Avoiding duplication 113 Disposing of resources 127
5
Exception Handling 131
Technical requirements 132 Creating custom exceptions and
Overview of exception handling in C#132 when to use them 147
try-catch132 Avoiding common mistakes in
try-catch-finally133 exception handling 149
Testing exception handling 151
Clean code exception-handling
principles135 Unit testing exception handling 152
Integration testing exception handling 153
SRP136
End-to-end testing exception handling 155
OCP138
DIP142 An employee management example
of mocking and unit testing with
Best practices for handling exceptions144
correct exception handling 156
Handling the TPL
Summary161
AggregateException exception 145
Use await with try-catch inside async methods 145
Questions162
Flatten the exception hierarchy 146 Further reading 163
Handle individual exceptions 146
Handle exceptions as they occur 147
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
x Table of Contents
6
Unit Testing 165
Technical requirements 166 Using code coverage analysis in Visual Studio
2022178
Understanding unit testing 166
Ensuring your unit tests themselves are correct 179
Writing testable code 166
Using stubs in place of mocks 179
TDD168 Mocking data 180
An example of using the AAA TDD pattern 169
Integrating tests into the continuous
Choosing a testing framework 170 integration and deployment (CI/CD)
Testing framework attribute differences 172 pipeline184
TDD using MSTest 173 Integrating tests into an Azure DevOps CI/
TDD using NUnit 174 CD pipeline 184
TDD using xUnit 175
Problem tests 186
Running tests in Visual Studio 176
Summary188
Writing effective unit tests 177 Questions189
Further reading 189
7
Designing and Developing APIs 191
Technical requirements 191 Web API security with OWASP 210
What is an API? 192 Importance of OWASP adherence in C# API
APIs help different consumers build loosely development210
coupled applications 192 Creating an OWASP-compliant API 211
Idempotent and non-idempotent operations 193 Implementing OWASP-compliant two-factor
HTTP verbs 194 authentication (2FA) 215
Important API design topics you must consider196 OpenID Connect (OIDC) and OAuth 2.0
(OAuth2)219
How can clean code help API design and
development?198 Summary223
The API design process 200
Questions224
API security risks and their mitigations 202
Further reading 225
On-premises APIs versus cloud APIs 205
8
Addressing Cross-Cutting Concerns 227
A definition of cross-cutting concerns228 Transaction management 239
Importance and impact on software Validation241
development230 Auditing and compliance 242
Localization and internationalization 244
Common examples of cross-cutting
Logging and monitoring 246
concerns231
Logging231 Summary247
Error handling and exception management 232 Questions248
Caching236 Further reading 248
Performance optimization 237
9
AOP with PostSharp 251
Technical requirements 251 Adding a resource pool concern 273
AOP252 Adding a configuration settings concern 274
Adding an instrumentation concern 274
AOP frameworks 253
How AOP works with PostSharp 254 PostSharp and build pipeline
considerations275
Extending the aspect framework 255
Dynamic AOP with Castle.
Project – Cross-cutting concerns DynamicProxy276
reusable library 258
Summary278
Adding a caching concern 259
Questions278
Adding file logging capabilities 260
Adding an exception-handling concern 263 Further reading 278
Adding a security concern 264
Adding a validation concern 267
Adding a transaction concern 272
xii Table of Contents
10
Using Tools to Improve Code Quality 279
Technical requirements 280 Continuous integration with GitHub
Code analysis 280 Actions and CodeQL 296
Using quick actions 282 Summary298
Using the JetBrains dotTrace profiler 283 Questions298
Using JetBrains ReSharper 285 Further reading 299
Using Telerik JustDecompile 295
11
Refactoring C# Code 301
Technical requirements 302 The lazy class (the freeloader and the lazy
object)323
Application-level code smells 302
The middleman class 323
Boolean blindness 302
The orphan class of variables and constants 323
Combinatorial explosion 304
Primitive obsession 324
Contrived complexity 305
Refused bequest 326
Data clump 306
Speculative generality 327
Deodorant comments 307
Tell, Don’t Ask 327
Duplicate code 307
Temporary fields 327
Lost intent 308
The mutation of variables 308 Method-level smells 327
The oddball solution 311 The black sheep method 327
Shotgun surgery 313 Cyclomatic complexity 327
Solution sprawl 314 Contrived complexity 328
Uncontrolled side effects 315 Dead code 328
Excessive data return 328
Class-level code smells 315
Feature envy 328
Cyclomatic complexity 315
Identifier size 328
Divergent change 319
Inappropriate intimacy 329
Downcasting320
Long lines (God lines) 329
Excessive literal use 320
Lazy methods 329
Feature envy 320
Long methods (God methods) 329
Inappropriate intimacy 322
Long parameter lists (too many parameters) 329
Indecent exposure 322
Message chains 329
The large class (the God object) 323
Table of Contents xiii
12
Functional Programming 333
Technical requirements 334 Functional error handling 348
Imperative versus functional Option types 349
programming334 The Maybe monad 349
Imperative programming 334 The Either monad 349
Key differences 336 Result objects 350
13
Cross-Platform Application Development with MAUI 367
Technical requirements 368 Creating the project 374
Project overview 368 Understanding XAML structure 377
Windows version 368 The MVVM pattern 379
Android version 370 Adding CommunityToolkit.Mvvm 380
The models 381
xiv Table of Contents
14
Microservices395
What are microservices? 396 Event-driven communication 412
The downsides of microservices, some Service resilience and fault tolerance 414
gotchas experienced by microservices, and
Service monitoring and observability 415
how they can be overcome and avoided 398
Service monitoring 416
Comparison between microservices and
monoliths400 Observability416
Assessments431
Chapter 1 431 Chapter 5 433
Chapter 2 431 Chapter 6 434
Chapter 3 432 Chapter 7 435
Chapter 4 432 Chapter 8 436
Table of Contents xv
Index445
Chapter 5, Exception Handling, covers checked and unchecked exceptions, and NullPointerEx-
ception, and how to avoid them as well as covering, business rule exceptions, providing meaningful
data, and building your own custom exceptions.
Chapter 6, Unit Testing, takes you through using the Behavior-Driven Development (BDD) software
methodology using SpecFlow, and Test-Driven Development (TDD) using MSTest and NUnit. You
will learn how to write mock (fake) objects using Moq, and how to use the TDD software methodology
to write tests that fail, make the tests pass, and then refactor the code once it passes.
Chapter 7, Designing and Developing APIs, helps you to understand what an API is, and covers API
proxies, API design guidelines, API design using RAML, and Swagger API development. In this chapter,
you will design a language-agnostic API in RAML and develop it in C#, and you will document your
API using Swagger.
Chapter 8, Addressing Cross-Cutting Concerns, introduces you to using PostSharp to address cross-
cutting concerns using aspects and attributes that form the basis of aspect-oriented development. You
will also learn how to use proxies and decorators.
Chapter 9, AOP with PostSharp, explores using PostSharp to implement Aspect-Oriented Programming
(AOP). With our AOP framework, we will learn how to manage common functionalities such as
exception handling, logging, security, and transactions within our applications. But before that, let’s
put your brain to work to see what you have learned.
Chapter 10, Using Tools to Improve Code Quality, exposes you to various tools that will assist you in
writing quality code and improving the quality of existing code. You’ll gain exposure to code metrics
and code analysis, quick actions, the JetBrains tools called dotTrace Profiler and Resharper, and
Telerik JustDecompile.
Chapter 11, Refactoring C# Code, is the first of two chapters that take you through different types
of problematic code and show you how to modify it to be clean code that is easy to read, maintain,
and extend. Code problems are listed alphabetically through each chapter. Here, you will cover such
topics as class dependencies, code that can’t be modified, collections, and combinatorial explosion.
Chapter 12, Functional Programming, provides a detailed look at functional programming. You will learn
the difference between imperative and functional programming. Then you will learn about delegates,
anonymous methods, and lambda expressions Next, you move on to the topics of asynchronous
functional programming, recursion, and then finally, pattern matching.
Chapter 13, Cross-platform development with MAUI, delves into building applications with .NET
MAUI. You will learn the differences between the older Xamarin.Forms and the newer MAUI,
including using UI controls using the MVVM pattern, data binding, access device resources, data
access accessing remote microservices and Azure Functions, dependency injection, and styling.
Chapter 14, Microservices, looks at developing microservices using Azure Functions.
Preface xix
It will be useful to have these in place before you start reading and working your way through the chapters.
If you are using the digital version of this book, we advise you to type the code yourself or access
the code from the book’s GitHub repository (a link is available in the next section). Doing so will
help you avoid any potential errors related to the copying and pasting of code.
You should have basic experience using Visual Studio 2019 Community Edition or higher, and basic
C# programming skills, including writing console applications. Many examples will be in the form
of C# console applications. The main project use ASP.NET. It will help if you are capable of writing
ASP.NET websites using the framework and core. However, don’t worry – you will be guided through
the steps that you need to go through.
Conventions used
There are a number of text conventions used throughout this book.
Code in text: 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
InMemoryRepository class implements the GetApiKey() method of IRepository. This
returns a dictionary of API keys. These keys will be stored in our_apiKeys dictionary member variable”
A block of code is set as follows:
using CH10_DividendCalendar.Security.Authentication;
using System.Threading.Tasks;
namespace CH10_DividendCalendar.Repository {
public interface IRepository
{
Task<ApiKey> GetApiKey(string providedApiKey);
}
}
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words
in menus or dialog boxes appear in bold. Here is an example: “To create the app service, right-click
the project you created and select Publish from the menu.”
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
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.packtpub.com/support/errata and fill in the form.
Preface xxi
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.
https://packt.link/free-ebook/9781837635191
We’ll now look at the technical requirements that you will need as you work through this book.
Technical requirements
To work on the code in this book, you will need to download and install the latest version of Visual
Studio Community Edition. The IDE can be downloaded from https://visualstudio.
microsoft.com.
Note
There are no code samples for this chapter.
Language: French
1917
PARIS
ERNEST FLAMMARION, ÉDITEUR
26, RUE RACINE, 26
THÉÂTRE
Copyright 1917,
by Ernest Flammarion.
ARLETTE DES MAYONS
Chacun de nous travaille
à refaire la France.
I
LE DÉPIQUAGE DU BLÉ