Clean Code in C#: Refactor your legacy C# code base and improve application performance by applying best practices

Clean Code in C#: Refactor your legacy C# code base and improve application performance by applying best practices

Clean Code in C#: Refactor your legacy C# code base and improve application performance by applying best practices
Автор: Alls Jason
Дата выхода: 2020
Издательство: Packt Publishing Limited
Количество страниц: 487
Размер файла: 6.0 MB
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы  Дополнительные материалы 

Cover....1

Title Page....2

Copyright and Credits....3

Dedication....4

About Packt....5

Contributors....6

Table of Contents....8

Preface....16

Chapter 1: Coding Standards and Principles in C#....22

Technical requirements....23

Good code versus bad code....24

Bad code....24

Improper indentation....25

Comments that state the obvious....25

Comments that excuse bad code....26

Commented-out lines of code....27

Improper organization of namespaces....27

Bad naming conventions....28

Classes that do multiple jobs....28

Methods that do many things....31

Methods with more than 10 lines of code....32

Methods with more than two parameters....33

Using exceptions to control program flow....33

Code that is difficult to read....34

Code that is tightly coupled....35

Low cohesion....36

Objects left hanging around....36

Use of the Finalize() method....37

Over-engineering....37

Learn to Keep It Simple, Stupid....37

Lack of regions in large classes....38

Lost-intention code....38

Directly exposing information....39

Good code....39

Proper indentation....40

Meaningful comments....40

API documentation comments....40

Proper organization using namespaces....41

Good naming conventions....41

Classes that only do one job....42

Methods that do one thing....42

Methods with less than 10 lines, and preferably no more than 4....42

Methods with no more than two parameters....43

Proper use of exceptions....43

Code that is readable....43

Code that is loosely coupled....44

High cohesion....44

Objects are cleanly disposed of....44

Avoiding the Finalize() method....45

The right level of abstraction....45

Using regions in large classes....46

The need for coding standards, principles, and methodologies....46

Coding standards....46

Coding principles....47

Coding methodologies....47

Coding conventions....48

Modularity....48

KISS....49

YAGNI....49

DRY....50

SOLID....50

Occam's Razor....51

Summary....51

Questions....52

Further reading....52

Chapter 2: Code Review – Process and Importance....53

The code review process....54

Preparing code for review....55

Leading a code review....56

Issuing a pull request....58

Responding to a pull request....61

Effects of feedback on reviewees....63

Knowing what to review....66

Company's coding guidelines and business requirement(s)....66

Naming conventions....66

Formatting....67

Testing....67

Architectural guidelines and design patterns....69

Performance and security....69

Knowing when to send code for review....70

Providing and responding to review feedback....72

Providing feedback as a reviewer....72

Responding to feedback as a reviewee....73

Summary....74

Questions....74

Further reading....75

Chapter 3: Classes, Objects, and Data Structures....76

Technical requirements....77

Organizing classes ....77

A class should have only one responsibility....80

Commenting for documentation generation....82

Cohesion and coupling....85

An example of tight coupling....86

An example of low coupling....87

An example of low cohesion....88

An example of high cohesion....89

Design for change....90

Interface-oriented programming....91

Dependency injection and inversion of control....94

An example of DI....94

An example of IoC....96

The Law of Demeter ....98

A good and a bad example (chaining) of the Law of Demeter....98

Immutable objects and data structures....100

An example of an immutable type....101

Objects should hide data and expose methods....102

An example of encapsulation....102

Data structures should expose data and have no methods....103

An example of data structure....104

Summary....104

Questions....105

Further reading....105

Chapter 4: Writing Clean Functions....106

Understanding functional programming....107

Keeping methods small....110

Indenting code....112

Avoiding duplication....114

Avoiding multiple parameters....115

Implementing SRP....117

Summary....122

Questions....122

Further reading....123

Chapter 5: Exception Handling....124

Checked and unchecked exceptions....125

Avoiding NullPointerExceptions....129

Business rule exceptions....132

Example 1 – handling conditions with business rule exceptions....135

Example 2 – handling conditions with normal program flow....136

Exceptions should provide meaningful information....138

Building your own custom exceptions....140

Summary....143

Questions....144

Further reading....144

Chapter 6: Unit Testing....145

Technical Requirements....146

Understanding the reasons for a good test....146

Understanding the testing tools....152

MSTest....152

NUnit....160

Moq....167

SpecFlow....172

TDD methodology practice – fail, pass, and refactor....177

Removing redundant tests, comments, and dead code....184

Summary....186

Questions....186

Further reading....187

Chapter 7: End-to-End System Testing....188

E2E testing....188

The login module (subsystem)....190

The admin module (subsystem)....194

The test module (subsystem)....196

Testing our three-module system using E2E....197

Factories....200

Dependency injection....209

Modularization....215

Summary....217

Questions....218

Further reading....218

Chapter 8: Threading and Concurrency....219

Understanding the thread life cycle....220

Adding thread parameters....222

Using a thread pool....223

Task Parallel Library....224

Parallel.Invoke()....224

Parallel.For()....225

ThreadPool.QueueUserWorkItem()....227

Using a mutex with synchronous threads....227

Working with parallel threads using semaphores....230

Limiting the number of processors and threads in the thread pool....232

Preventing deadlocks....234

Coding a deadlock example....235

Preventing race conditions....240

Understanding static constructors and methods ....243

Adding static constructors to our sample code....244

Adding static methods to our sample code....245

Mutability, immutability, and thread safety....249

Writing code that is mutable and not thread-safe....249

Writing code that is immutable and thread-safe ....251

Understanding thread safety....253

Synchronized method dependencies....257

Using the Interlocked class....258

General recommendations....262

Summary....263

Questions....264

Further reading....264

Chapter 9: Designing and Developing APIs....266

Technical requirements....267

What is an API?....267

API proxies....269

API design guidelines....271

Well-defined software boundaries....274

Understanding the importance of good quality API documentation ....276

Swagger API development....277

Passing immutable structs instead of mutable objects....280

Testing third-party APIs....283

Testing your own APIs....284

API design using RAML....286

Installing Atom and API Workbench by MuleSoft....287

Creating the project....289

Generating our C# API from our agnostic RAML design specification....292

Summary....296

Questions....296

Further reading....297

Chapter 10: Securing APIs with API Keys and Azure Key Vault....298

Technical requirements....299

Undertaking the API project – dividend calendar....299

Accessing the Morningstar API....301

Storing the Morningstar API key in Azure Key Vault....301

Creating the dividend calendar ASP.NET Core web application in Azure....304

Publishing our web application....306

Using an API key to secure our dividend calendar API....312

Setting up the repository....312

Setting up authentication and authorization....315

Adding authentication....315

Adding authorization....319

Testing our API key security....323

Adding the dividend calendar code....326

Throttling our API ....334

Summary....338

Questions....339

Further reading....339

Chapter 11: Addressing Cross-Cutting Concerns....341

Technical requirements....342

The decorator pattern....342

The proxy pattern....346

AOP with PostSharp....348

Extending the aspect framework....349

Developing our aspect....349

Injecting behaviors before and after the method execution....349

Extending the architectural framework....352

Project – cross-cutting concerns reusable library....353

Adding the caching concern....353

Adding file logging capabilities....355

Adding the logging concern....356

Adding the exception-handling concern....357

Adding the security concern....359

Adding the validation concern....363

Adding the transaction concern....367

Adding the resource pool concern....368

Adding the configuration settings concern....369

Adding the instrumentation concern....370

Summary....371

Questions....371

Further reading....371

Chapter 12: Using Tools to Improve Code Quality....372

Technical requirements....373

Defining good-quality code....373

Performing code cleanup and calculating code metrics ....375

Performing code analysis....378

Using quick actions....381

Using the JetBrains dotTrace profiler....382

Using JetBrains ReSharper....387

Using Telerik JustDecompile....397

Summary....399

Questions....400

Further reading....400

Chapter 13: Refactoring C# Code – Identifying Code Smells....401

Technical requirements....402

Application-level code smells....402

Boolean blindness....402

Combinatorial explosion....404

Contrived complexity....405

Data clump....406

Deodorant comments ....406

Duplicate code....407

Lost intent....407

The mutation of variables....408

The oddball solution....410

Shotgun surgery....412

Solution sprawl....414

Uncontrolled side effects....414

Class-level code smells....415

Cyclomatic complexity....415

Replacing switch statements with the factory pattern....415

Improving the readability of conditional checks within an if statement....418

Divergent change....419

Downcasting....420

Excessive literal use....420

Feature envy....420

Inappropriate intimacy....422

Indecent exposure....423

The large class (aka the God object)....423

The lazy class (aka the freeloader and the lazy object)....423

The middleman class....424

The orphan class of variables and constants....424

Primitive obsession....424

Refused bequest....425

Speculative generality....425

Tell, Don't Ask....425

Temporary fields....425

Method-level smells....426

The black sheep method....426

Cyclomatic complexity....426

Contrived complexity....426

Dead code....426

Excessive data return....427

Feature envy....427

Identifier size....427

Inappropriate intimacy....427

Long lines (aka God lines)....428

Lazy methods....428

Long methods (aka God methods)....428

Long parameter lists (aka too many parameters)....428

Message chains....428

The middleman method....429

Oddball solutions....429

Speculative generality....429

Summary....429

Questions....430

Further reading....431

Chapter 14: Refactoring C# Code – Implementing Design Patterns....432

Technical requirements....433

Implementing creational design patterns....433

Implementing the singleton pattern....434

Implementing the factory method pattern....435

Implementing the abstract factory pattern....437

Implementing the prototype pattern....440

Implementing the builder pattern....442

Implementing structural design patterns....448

Implementing the bridge pattern....449

Implementing the composite pattern....451

Implementing the façade pattern....454

Implementing the flyweight pattern....457

Overview of behavioral design patterns....460

Final thoughts....461

Summary....463

Questions....464

Further reading....465

Assessments....466

Chapter 1....466

Chapter 2....466

Chapter 3....467

Chapter 4....467

Chapter 5....468

Chapter 6....469

Chapter 7....470

Chapter 8....470

Chapter 9....471

Chapter 10....472

Chapter 11....472

Chapter 12....473

Chapter 13....473

Chapter 14....475

Other Books You May Enjoy....477

Index....480

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.

What you will learn

  • Write code that allows software to be modified and adapted over time
  • Implement the fail-pass-refactor methodology using a sample C# console application
  • Address cross-cutting concerns with the help of software design patterns
  • Write custom C# exceptions that provide meaningful information
  • Identify poor quality C# code that needs to be refactored
  • Secure APIs with API keys and protect data using Azure Key Vault
  • Improve your code's performance by using tools for profiling and refactoring

Who this book is for

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.


Похожее:

Список отзывов:

Нет отзывов к книге.