Clean Code with C#....2
Contributors....7
About the author....7
About the reviewers....8
Preface....34
Who this book is for....35
What this book covers....36
To get the most out of this book....40
Download the example code files....42
Conventions used....42
Get in touch....43
Share Your Thoughts....44
Download a free PDF copy of this book....45
Chapter 1: Coding Standards and Principles in C#....47
Technical requirements....49
Good code versus bad code....49
The need for coding standards, principles, and methodologies....52
Coding standards....54
Coding principles....55
Coding methodologies....68
Summary....94
Questions....96
Further reading....96
Chapter 2: Code Review – Process and Importance....100
A brief introduction to GitHub....102
What is GitHub?....103
GitHub’s use within the code review process....104
Resources for learning....107
The code review process....109
Preparing code for review....110
Leading a code review....114
Issuing a pull request....116
Responding to a pull request....123
Effects of feedback on reviewees....127
Knowing what to review....131
The company’s coding guidelines and business requirement(s)....132
Naming conventions....133
Formatting....133
Testing....134
Documentation....137
Architectural guidelines and design patterns....138
Performance and security....140
Knowing when to send code for review....141
Providing and responding to review feedback....143
Providing feedback as a reviewer....144
Responding to feedback as a reviewee....145
Summary....146
Questions....148
Further reading....148
Chapter 3: Classes, Objects, and Data Structures....150
Technical requirements....151
Organizing classes....152
A class should have only one responsibility....158
Class organization....161
Commenting for documentation generation....164
Cohesion and coupling....171
Tight coupling....173
Low coupling....175
Low cohesion....178
High cohesion....180
Designing for change....182
Interface-oriented programming....183
Dependency injection and inversion of control....188
The Law of Demeter....201
A good and a bad example (chaining) of the Law of Demeter....204
Immutable objects and data structures....207
Using records to create immutable objects....210
Objects should hide data and expose methods....212
An example of encapsulation....213
Data structures should expose data and have no methods....215
The SOLID software methodology....216
SRP....217
Open/closed principle (OCP)....218
Liskov substitution principle (LSP)....219
Interface segregation principle (ISP)....222
Dependency inversion principle (DIP)....223
Summary....225
Questions....226
Further reading....227
Chapter 4: Writing Clean Functions....229
Technical requirements....231
Understanding the difference between OOP and FP....231
Explanation of the differences....233
Understanding why FP can lead to cleaner functions....235
Unclean methods and how they affect software....238
FP and clean methods....242
FP examples....246
Keeping methods small....254
Indenting code....258
Breaking out of loops....259
Avoiding duplication....261
Avoiding multiple parameters....265
Implementing the SRP....268
Handling exceptions in FP....279
Adding comments for readability....284
XML documentation comments....284
Inline comments....285
Variable declaration and memory management....285
Declaring variables close to their usage....286
Disposing of resources....286
Applying security in methods, especially in APIs....287
Input validation....287
Authentication and authorization....288
Protecting sensitive data....288
Summary....289
Questions....290
Further reading....291
Chapter 5: Exception Handling....292
Technical requirements....293
Overview of exception handling in C#....294
try-catch....294
try-catch-finally....296
Clean code exception-handling principles....299
SRP....301
OCP....306
DIP....312
Best practices for handling exceptions....316
Handling the TPL AggregateException exception....319
Use await with try-catch inside async methods....320
Flatten the exception hierarchy....320
Handle individual exceptions....321
Handle exceptions as they occur....322
Creating custom exceptions and when to use them....323
Avoiding common mistakes in exception handling....325
Testing exception handling....330
Unit testing exception handling....331
Integration testing exception handling....333
End-to-end testing exception handling....338
An employee management example of mocking and unit testing with correct exception handling....339
Summary....348
Questions....349
Further reading....351
Chapter 6: Unit Testing....353
Technical requirements....353
Understanding unit testing....354
Writing testable code....354
TDD....355
An example of using the AAA TDD pattern....357
Choosing a testing framework....358
Testing framework attribute differences....360
TDD using MSTest....361
TDD using NUnit....362
TDD using xUnit....363
Running tests in Visual Studio....365
Writing effective unit tests....366
Using code coverage analysis in Visual Studio 2022....367
Ensuring your unit tests themselves are correct....367
Using stubs in place of mocks....368
Mocking data....369
Integrating tests into the continuous integration and deployment (CI/CD) pipeline....372
Integrating tests into an Azure DevOps CI/CD pipeline....372
Problem tests....374
Summary....375
Questions....376
Further reading....376
Chapter 7: Designing and Developing APIs....378
Technical requirements....379
What is an API?....379
APIs help different consumers build loosely coupled applications....381
Idempotent and non-idempotent operations....383
HTTP verbs....385
Important API design topics you must consider....388
How can clean code help API design and development?....393
The API design process....397
API security risks and their mitigations....402
On-premises APIs versus cloud APIs....407
API development in C#....411
Web API security with OWASP....416
Importance of OWASP adherence in C# API development....418
Creating an OWASP-compliant API....420
Implementing OWASP-compliant two-factor authentication (2FA)....424
OpenID Connect (OIDC) and OAuth 2.0 (OAuth2)....430
Summary....438
Questions....440
Further reading....441
Chapter 8: Addressing Cross-Cutting Concerns....444
A definition of cross-cutting concerns....445
Importance and impact on software development....450
Common examples of cross-cutting concerns....452
Logging....452
Error handling and exception management....455
Caching....464
Performance optimization....467
Transaction management....472
Validation....476
Auditing and compliance....479
Localization and internationalization....483
Logging and monitoring....488
Summary....490
Questions....492
Further reading....492
Chapter 9: AOP with PostSharp....495
Technical requirements....496
AOP....496
AOP frameworks....500
How AOP works with PostSharp....503
Extending the aspect framework....504
Project – Cross-cutting concerns reusable library....512
Adding a caching concern....514
Adding file logging capabilities....517
Adding an exception-handling concern....522
Adding a security concern....524
Adding a validation concern....531
Adding a transaction concern....541
Adding a resource pool concern....542
Adding a configuration settings concern....543
Adding an instrumentation concern....545
PostSharp and build pipeline considerations....547
Dynamic AOP with Castle.DynamicProxy....548
Summary....551
Questions....552
Further reading....552
Chapter 10: Using Tools to Improve Code Quality....554
Technical requirements....555
Code analysis....555
Using quick actions....558
Using the JetBrains dotTrace profiler....560
Using JetBrains ReSharper....565
Using Telerik JustDecompile....581
Continuous integration with GitHub Actions and CodeQL....584
Summary....585
Questions....587
Further reading....587
Chapter 11: Refactoring C# Code....589
Technical requirements....590
Application-level code smells....590
Boolean blindness....591
Combinatorial explosion....594
Contrived complexity....596
Data clump....599
Deodorant comments....600
Duplicate code....601
Lost intent....603
The mutation of variables....604
The oddball solution....609
Shotgun surgery....612
Solution sprawl....616
Uncontrolled side effects....616
Class-level code smells....618
Cyclomatic complexity....618
Divergent change....626
Downcasting....626
Excessive literal use....627
Feature envy....628
Inappropriate intimacy....631
Indecent exposure....631
The large class (the God object)....632
The lazy class (the freeloader and the lazy object)....633
The middleman class....634
The orphan class of variables and constants....634
Primitive obsession....636
Refused bequest....640
Speculative generality....641
Tell, Don’t Ask....641
Temporary fields....642
Method-level smells....642
The black sheep method....643
Cyclomatic complexity....643
Contrived complexity....643
Dead code....644
Excessive data return....644
Feature envy....645
Identifier size....645
Inappropriate intimacy....646
Long lines (God lines)....646
Lazy methods....647
Long methods (God methods)....647
Long parameter lists (too many parameters)....647
Message chains....648
The middleman method....648
Oddball solutions....648
Speculative generality....649
Summary....649
Questions....651
Further reading....653
Chapter 12: Functional Programming....654
Technical requirements....655
Imperative versus functional programming....655
Imperative programming....655
Key differences....660
Overview of functional programming in C#....663
First-class functions and Lambda expressions....666
Lambda expressions in C#....667
Higher-order functions....668
Immutability and pure functions....672
Functional composition....675
Using Lambda expressions....676
Using LINQ and extension methods....676
Using higher-order functions....677
Option types and the Maybe monad....678
Usage of option types in C#....681
The Maybe monad in C#....682
Functional error handling....684
Option types....687
The Maybe monad....687
The Either monad....687
Result objects....688
Functional data transformation and pipelines....689
Lazy evaluation....695
Pattern matching....698
Currying and partial application....702
Currying....702
Partial application....703
Key differences....703
Concurrency with functional programming....704
Recursion....712
Summary....715
Questions....717
Further reading....718
Chapter 13: Cross-Platform Application Development with MAUI....720
Technical requirements....721
Project overview....721
Windows version....722
Android version....724
Creating the project....732
Understanding XAML structure....738
The MVVM pattern....740
Adding CommunityToolkit.Mvvm....743
The models....745
The ViewModels....750
The views....757
Configuring our to-do application....764
Summary....765
Questions....767
Further reading....768
Chapter 14: Microservices....769
What are microservices?....771
The downsides of microservices, some gotchas experienced by microservices, and how they can be overcome and avoided....774
Comparison between microservices and monoliths....779
The design process for building successful microservices....783
The application life cycle management (ALM) of microservices....787
Microservice architecture patterns....792
Service registration and discovery....796
Service discovery....796
Service registration....799
Containerization and orchestration of microservices....800
Containerization....800
Orchestration....802
Serverless....804
API gateways....806
Event-driven communication....809
Service resilience and fault tolerance....812
Service monitoring and observability....816
Service monitoring....816
Observability....817
Security....819
CI/CD....822
Microservice testing....826
Scaling microservices....830
Versioning and compatibility....833
Microservices best practices and anti-patterns....837
Microservices best practices....837
Microservices anti-patterns....838
Case studies and real-world examples....842
Summary....845
Questions....847
Further reading....848
Assessments....850
Chapter 1....851
Chapter 2....853
Chapter 3....854
Chapter 4....856
Chapter 5....858
Chapter 6....860
Chapter 7....862
Chapter 8....864
Chapter 9....865
Chapter 10....866
Chapter 11....868
Chapter 12....875
Chapter 13....877
Chapter 14....881
Index....883
Why subscribe?....951
Other Books You May Enjoy....952
Packt is searching for authors like you....955
Share Your Thoughts....956
Download a free PDF copy of this book....956
Traditionally associated with developing Windows desktop applications and games, C# is now used in a wide variety of domains, such as web and cloud apps, and has become increasingly popular for mobile development. Despite its extensive coding features, professionals experience problems related to efficiency, scalability, and maintainability because of bad code. Clean Code in C# will help you identify these problems and solve them using coding best practices.
The book starts with a comparison of good and bad code, helping you understand the importance of coding standards, principles, and methodologies. You'll then get to grips with code reviews and their role in improving your code while ensuring that you adhere to industry-recognized coding standards. This C# book covers unit testing, delves into test-driven development, and addresses cross-cutting concerns. You'll explore good programming practices for objects, data structures, exception handling, and other aspects of writing C# computer programs. Once you've studied API design and discovered tools for improving code quality, you'll look at examples of bad code and understand which coding practices you should avoid.
By the end of this clean code book, you'll have the developed skills you need in order to apply industry-approved coding practices to write clean, readable, extendable, and maintainable C# code.
This coding book is for C# developers, team leads, senior software engineers, and software architects who want to improve the efficiency of their legacy systems. A strong understanding of C# programming is required.