Preface

Welcome to Clean Code in C#. You will learn how to identify problematic code that, while it compiles, does not lend itself to readability, maintainability, and extensibility. You will also learn about various tools and patterns, along with ways to refactor code to make it clean.

Who this book is for

This book is aimed at computer programmers with a good grasp of the C# programming language who would like guidance on identifying problematic code and writing clean code in C#. Primarily, the reader base will range from graduate to mid-level programmers, but even senior programmers may find this book valuable.

What this book covers

Chapter 1, Coding Standards and Principles in C#, looks at some good code contrasted with bad code. As you read through this chapter, you will come to understand why you need coding standards, principles, methodologies, and code conventions. You will learn about modularity and the design guidelines KISS, YAGNI, DRY, SOLID, and Occam's razor.

Chapter 2, Code Review – Process and Importance, takes you through the code review process and provides reasons for its importance. In this chapter, you are guided through the process of preparing code for review, leading a code review, knowing what to review, knowing when to send code for review, and how to provide and respond to review feedback.

Chapter 3, Classes, Objects, and Data Structures, covers the broad topics of class organization, documentation comments, cohesion, coupling, the Law of Demeter, and immutable objects and data structures. By the end of the chapter, you will be able to write code that is well organized and only has a single responsibility, provide users of the code with relevant documentation, and make code extensible.

Chapter 4, Writing Clean Functions, helps you to understand functional programming, how to keep methods small, and how to avoid code duplication and multiple parameters. By the time you finish this chapter, you will be able to describe functional programming, write functional code, avoid writing code with more than two parameters, write immutable data objects and structures, keep your methods small, and write code that adheres to the Single Responsibility Principle.

Chapter 5, Exception Handling, covers checked and unchecked exceptions, NullPointerException, 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, End-to-End System Testing, guides you through the manual process of end-to-end testing using an example project. In this chapter, you will perform End-to-End (E2E) testing, code and test factories, code and test dependency injection, and test modularization. You will also learn how to utilize modularization.

Chapter 8, Threading and Concurrency, focuses on understanding the thread life cycle; adding parameters to threads; using ThreadPool, mutexes, and synchronous threads; working with parallel threads using semaphores; limiting the number of threads and processors used by ThreadPool; preventing deadlocks and race conditions; static methods and constructors; mutability and immutability; and thread-safety.

Chapter 9, Designing and Developing APIs, helps you to understand what an API is, 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 10, Securing APIs with API Keys and Azure Key Vault, shows you how to obtain a third-party API key, store that key in Azure Key Vault, and retrieve it via an API that you will build and deploy to Azure. You will then implement API key authentication and authorization to secure your own API.

Chapter 11, 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 12, 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 13, Refactoring C# Code – Identifying Code Smells, 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 14, Refactoring C# Code – Implementing Design Patterns, takes you through the implementation of creational and structural design patterns. Here, behavioral design patterns are briefly touched upon. You are then given some final thoughts on clean code and refactoring.

To get the most out of this book

The majority of the chapters can be read independently of each other and in any order. But to get the most out of this book, I recommend that you read the chapters in the order presented. As you work through the chapters, follow the instructions, and carry out the tasks presented. Then, when you reach the end of a chapter, answer the questions and carry out the recommended further reading to reinforce what you have learned. For maximum benefit when working through the contents of this book, it is recommended that you meet the following requirements:

It will be useful if you 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 via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related tothe copying and pasting of code.

You should have basic experience of 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 will be using ASP.NET. It will help if you are capable of writing ASP.NET websites using the framework and core. But don't worry – you will be guided through the steps that you need to go through.

Download the example code files

You can download the example code files for this book from your account atwww.packt.com. If you purchased this book elsewhere, you can visitwww.packtpub.com/supportand register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register atwww.packt.com.
  2. Select theSupporttab.
  3. Click onCode Downloads.
  4. Enter the name of the book in theSearchbox 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 athttps://github.com/PacktPublishing/Clean-Code-in-C-. 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 athttps://github.com/PacktPublishing/. Check them out!

Download the color images

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/9781838982973_ColorImages.pdf.

Conventions used

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 InMemoryRepository class implements theGetApiKey()method ofIRepository. This returns a dictionary of API keys. These keys will be stored in our_apiKeysdictionary 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);
}
}

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

          az group create --name "<YourResourceGroupName>" --location "East US"
        

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: "To create the app service, right-click the project you created and select Publish from the menu."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

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 atcustomercare@packtpub.com.

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 visitwww.packtpub.com/support/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 atcopyright@packt.comwith 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 visitauthors.packtpub.com.

Reviews

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.