Alls Jason / Оллс Джейсон - Clean Code with C#, 2nd Edition / Чистый код на C#, 2-е издание [2023, PDF/EPUB, ENG]

Страницы:  1
Ответить
 

tsurijin

Стаж: 4 года 8 месяцев

Сообщений: 2787


tsurijin · 25-Дек-23 09:24 (1 год 6 месяцев назад, ред. 25-Дек-23 09:33)

Clean Code with C#: Refactor your legacy C# code base and improve application performance using best practices, 2nd Edition / Чистый код на C#: Рефакторинг устаревшей кодовой базы C# и повышение производительности приложений с помощью лучших практик, 2-е издание
Год издания: 2023
Автор: Alls Jason / Оллс Джейсон
Издательство: Packt Publishing
ISBN: 978-1-83763-519-1
Язык: Английский
Формат: PDF, EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 492
Описание: Enhance your programming skills through code reviews, TDD and BDD implementation, and API design to overcome code inefficiency, redundancy, and other issues arising from bad code
Key Features
Write code that seamlessly integrates with other systems while maintaining well-defined software boundaries
Understand how coding principles and standards elevate software quality
Learn how to avoid common errors while implementing concurrency or threading
Book Description
Traditionally associated with Windows desktop applications and game development, C# has expanded into web, cloud, and mobile development. However, despite its extensive coding features, professionals often encounter issues with efficiency, scalability, and maintainability due to poor code. Clean Code in C# guides you in identifying and resolving these problems using coding best practices.
This book starts by comparing good and bad code to emphasize the importance of coding standards, principles, and methodologies. It then covers code reviews, unit testing, and test-driven development, and addresses cross-cutting concerns. As you advance through the chapters, you’ll discover programming best practices for objects, data structures, exception handling, and other aspects of writing C# computer programs. You’ll also explore API design and code quality enhancement tools, while studying examples of poor coding practices to understand what to avoid.
By the end of this clean code book, you’ll have the developed the skills needed to apply industry-approved coding practices to write clean, readable, extendable, and maintainable C# code.
What you will learn
Master the art of writing evolvable and adaptable code
Implement the fail-pass-refactor methodology using a sample C# console application
Develop custom C# exceptions that provide meaningful information
Identify low-quality C# code in need of refactoring
Improve code performance using profiling and refactoring tools
Create efficient and bug-free code using functional programming techniques
Write cross-platform code using MAUI
Develop cloud-deployable microservices for versatile applications
Who this book is for
This coding book is for proficient 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 assumed.
Совершенствуйте свои навыки программирования с помощью обзоров кода, реализации TDD и BDD и разработки API, чтобы преодолеть неэффективность кода, избыточность и другие проблемы, возникающие из-за плохого кода
Ключевые функции
Напишите код, который легко интегрируется с другими системами, сохраняя при этом четко определенные границы программного обеспечения
Поймите, как принципы и стандарты кодирования повышают качество программного обеспечения
Узнайте, как избежать распространенных ошибок при реализации параллелизма или многопоточности
Описание книги
Традиционно ассоциируемый с настольными приложениями Windows и разработкой игр, C# распространился на веб-, облачную и мобильную разработку. Однако, несмотря на его обширные возможности кодирования, профессионалы часто сталкиваются с проблемами эффективности, масштабируемости и сопровождаемости из-за плохого кода. Чистый код на C# поможет вам выявить и устранить эти проблемы, используя лучшие практики кодирования.
Эта книга начинается со сравнения хорошего и плохого кода, чтобы подчеркнуть важность стандартов, принципов и методологий кодирования. Затем в ней рассматриваются обзоры кода, модульное тестирование и разработка на основе тестов, а также рассматриваются сквозные проблемы. По мере продвижения по главам вы познакомитесь с лучшими практиками программирования объектов, структур данных, обработки исключений и другими аспектами написания компьютерных программ на C#. Вы также познакомитесь с дизайном API и инструментами повышения качества кода, изучая примеры некачественных методов кодирования, чтобы понять, чего следует избегать.
К концу этой книги по чистому коду у вас будут развиты навыки, необходимые для применения одобренных отраслью методов кодирования для написания чистого, читаемого, расширяемого и поддерживаемого кода на C#.
Чему вы научитесь
Овладеете искусством написания эволюционирующего и адаптируемого кода
Внедрите методологию fail-pass-рефакторинга с использованием примера консольного приложения C#
Разработаете пользовательские исключения C#, которые предоставляют значимую информацию
Выявите некачественный код C#, нуждающийся в рефакторинге
Повысите производительность кода с помощью инструментов профилирования и рефакторинга
Создавать эффективный код без ошибок, используя методы функционального программирования
Писать кроссплатформенный код с использованием MAUI
Разрабатывать микросервисы с возможностью развертывания в облаке для универсальных приложений
Для кого предназначена эта книга
Эта книга по программированию предназначена для опытных разработчиков на C#, руководителей команд, старших инженеров-программистов и архитекторов программного обеспечения, которые хотят повысить эффективность своих устаревших систем. Предполагается глубокое понимание программирования на C#.
Примеры страниц
Оглавление
Preface xvii
1
Coding Standards and Principles in C# 1
Technical requirements 2
Good code versus bad code 2
The need for coding standards, principles, and methodologies 3
Coding standards 4
Coding principles 5
Coding methodologies 10
Summary 21
Questions 22
Further reading 23
2
Code Review – Process and Importance 25
A brief introduction to GitHub 26
What is GitHub? 26
GitHub’s use within the code review process 27
Resources for learning 28
The code review process 29
Preparing code for review 30
Leading a code review 32
Issuing a pull request 33
Responding to a pull request 37
Effects of feedback on reviewees 40
Knowing what to review 42
The company’s coding guidelines and business requirement(s) 43
Naming conventions 43
Formatting 43
Testing 44
Documentation 45
Architectural guidelines and design patterns 45
Performance and security 47
Knowing when to send code for review 47
Providing and responding to review feedback 48
Providing feedback as a reviewer 49
Responding to feedback as a reviewee 49
Summary 50
Questions 50
Further reading 51
3
Classes, Objects, and Data Structures 53
Technical requirements 54
Organizing classes 54
A class should have only one responsibility 58
Class organization 60
Commenting for documentation generation 61
Cohesion and coupling 65
Tight coupling 66
Low coupling 67
Low cohesion 68
High cohesion 70
Designing for change 71
Interface-oriented programming 71
Dependency injection and inversion of control 74
The Law of Demeter 81
A good and a bad example (chaining) of the Law of Demeter 83
Immutable objects and data structures 85
Using records to create immutable objects 87
Objects should hide data and expose methods 88
An example of encapsulation 88
Data structures should expose data and have no methods 89
The SOLID software methodology 90
SRP 90
Open/closed principle (OCP) 91
Liskov substitution principle (LSP) 91
Interface segregation principle (ISP) 93
Dependency inversion principle (DIP) 94
Summary 95
Questions 96
Further reading 96
4
Writing Clean Functions 97
Technical requirements 98
Understanding the difference between OOP and FP 98
Explanation of the differences 99
Understanding why FP can lead to cleaner functions 101
Unclean methods and how they affect software 102
FP and clean methods 104
FP examples 105
Keeping methods small 109
Indenting code 112
Breaking out of loops 113
Avoiding duplication 113
Avoiding multiple parameters 115
Implementing the SRP 117
Handling exceptions in FP 123
Adding comments for readability 125
XML documentation comments 125
Inline comments 126
Variable declaration and memory management 126
Declaring variables close to their usage 126
Disposing of resources 127
Applying security in methods, especially in APIs 127
Input validation 127
Authentication and authorization 128
Protecting sensitive data 128
Summary 128
Questions 129
Further reading 129
5
Exception Handling 131
Technical requirements 132
Overview of exception handling in C# 132
try-catch 132
try-catch-finally 133
Clean code exception-handling principles 135
SRP 136
OCP 138
DIP 142
Best practices for handling exceptions 144
Handling the TPL AggregateException exception 145
Use await with try-catch inside async methods 145
Flatten the exception hierarchy 146
Handle individual exceptions 146
Handle exceptions as they occur 147
Creating custom exceptions and when to use them 147
Avoiding common mistakes in exception handling 149
Testing exception handling 151
Unit testing exception handling 152
Integration testing exception handling 153
End-to-end testing exception handling 155
An employee management example of mocking and unit testing with correct exception handling 156
Summary 161
Questions 162
Further reading 163
6
Unit Testing 165
Technical requirements 166
Understanding unit testing 166
Writing testable code 166
TDD 168
An example of using the AAA TDD pattern 169
Choosing a testing framework 170
Testing framework attribute differences 172
TDD using MSTest 173
TDD using NUnit 174
TDD using xUnit 175
Running tests in Visual Studio 176
Writing effective unit tests 177
Using code coverage analysis in Visual Studio 2022 178
Ensuring your unit tests themselves are correct 179
Using stubs in place of mocks 179
Mocking data 180
Integrating tests into the continuous integration and deployment (CI/CD) pipeline 184
Integrating tests into an Azure DevOps CI/CD pipeline 184
Problem tests 186
Summary 188
Questions 189
Further reading 189
7
Designing and Developing APIs 191
Technical requirements 191
What is an API? 192
APIs help different consumers build loosely coupled applications 192
Idempotent and non-idempotent operations 193
HTTP verbs 194
Important API design topics you must consider 196
How can clean code help API design and development? 198
The API design process 200
API security risks and their mitigations 202
On-premises APIs versus cloud APIs 205
API development in C# 207
Web API security with OWASP 210
Importance of OWASP adherence in C# API development 210
Creating an OWASP-compliant API 211
Implementing OWASP-compliant two-factor authentication (2FA) 215
OpenID Connect (OIDC) and OAuth 2.0 (OAuth2) 219
Summary 223
Questions 224
Further reading 225
8
Addressing Cross-Cutting Concerns 227
A definition of cross-cutting concerns 228
Importance and impact on software development 230
Common examples of cross-cutting concerns 231
Logging 231
Error handling and exception management 232
Caching 236
Performance optimization 237
Transaction management 239
Validation 241
Auditing and compliance 242
Localization and internationalization 244
Logging and monitoring 246
Summary 247
Questions 248
Further reading 248
9
AOP with PostSharp 251
Technical requirements 251
AOP 252
AOP frameworks 253
How AOP works with PostSharp 254
Extending the aspect framework 255
Project – Cross-cutting concerns reusable library 258
Adding a caching concern 259
Adding file logging capabilities 260
Adding an exception-handling concern 263
Adding a security concern 264
Adding a validation concern 267
Adding a transaction concern 272
Adding a resource pool concern 273
Adding a configuration settings concern 274
Adding an instrumentation concern 274
PostSharp and build pipeline considerations 275
Dynamic AOP with Castle. DynamicProxy 276
Summary 278
Questions 278
Further reading 278
10
Using Tools to Improve Code Quality 279
Technical requirements 280
Code analysis 280
Using quick actions 282
Using the JetBrains dotTrace profiler 283
Using JetBrains ReSharper 285
Using Telerik JustDecompile 295
Continuous integration with GitHub
Actions and CodeQL 296
Summary 298
Questions 298
Further reading 299
11
Refactoring C# Code 301
Technical requirements 302
Application-level code smells 302
Boolean blindness 302
Combinatorial explosion 304
Contrived complexity 305
Data clump 306
Deodorant comments 307
Duplicate code 307
Lost intent 308
The mutation of variables 308
The oddball solution 311
Shotgun surgery 313
Solution sprawl 314
Uncontrolled side effects 315
Class-level code smells 315
Cyclomatic complexity 315
Divergent change 319
Downcasting 320
Excessive literal use 320
Feature envy 320
Inappropriate intimacy 322
Indecent exposure 322
The large class (the God object) 323
The lazy class (the freeloader and the lazy
object) 323
The middleman class 323
The orphan class of variables and constants 323
Primitive obsession 324
Refused bequest 326
Speculative generality 327
Tell, Don’t Ask 327
Temporary fields 327
Method-level smells 327
The black sheep method 327
Cyclomatic complexity 327
Contrived complexity 328
Dead code 328
Excessive data return 328
Feature envy 328
Identifier size 328
Inappropriate intimacy 329
Long lines (God lines) 329
Lazy methods 329
Long methods (God methods) 329
Long parameter lists (too many parameters) 329
Message chains 329
The middleman method 330
Oddball solutions 330
Speculative generality 330
Summary 330
Questions 331
Further reading 332
12
Functional Programming 333
Technical requirements 334
Imperative versus functional
programming 334
Imperative programming 334
Key differences 336
Overview of functional
programming in C# 338
First-class functions and Lambda
expressions 339
Lambda expressions in C# 339
Higher-order functions 340
Immutability and pure functions 342
Functional composition 343
Using Lambda expressions 343
Using LINQ and extension methods 344
Using higher-order functions 344
Option types and the Maybe monad 344
Usage of option types in C# 346
The Maybe monad in C# 346
Functional error handling 348
Option types 349
The Maybe monad 349
The Either monad 349
Result objects 350
Functional data transformation and pipelines 350
Lazy evaluation 353
Pattern matching 355
Currying and partial application 357
Currying 357
Partial application 357
Key differences 358
Concurrency with functional programming 358
Recursion 362
Summary 363
Questions 364
Further reading 364
13
Cross-Platform Application Development with MAUI 367
Technical requirements 368
Project overview 368
Windows version 368
Android version 370
Creating the project 374
Understanding XAML structure 377
The MVVM pattern 379
Adding CommunityToolkit.Mvvm 380
The models 381
The ViewModels 384
The views 387
Configuring our to-do application 391
Summary 392
Questions 392
Further reading 393
14
Microservices 395
What are microservices? 396
The downsides of microservices, some
gotchas experienced by microservices, and
how they can be overcome and avoided 398
Comparison between microservices and
monoliths 400
The design process for building
successful microservices 401
The application life cycle
management (ALM) of microservices 403
Microservice architecture patterns 405
Service registration and discovery 407
Service discovery 407
Service registration 408
Containerization and orchestration of microservices 409
Containerization 409
Orchestration 409
Serverless 410
API gateways 411
Event-driven communication 412
Service resilience and fault tolerance 414
Service monitoring and observability 415
Service monitoring 416
Observability 416
Security 417
CI/CD 418
Microservice testing 420
Scaling microservices 421
Versioning and compatibility 423
Microservices best practices and antipatterns 424
Microservices best practices 424
Microservices anti-patterns 425
Case studies and real-world examples 427
Summary 428
Questions 429
Further reading 429
Assessments 431
Chapter 1 431
Chapter 2 431
Chapter 3 432
Chapter 4 432
Chapter 5 433
Chapter 6 434
Chapter 7 435
Chapter 8 436
Chapter 9 436
Chapter 10 436
Chapter 11 437
Chapter 12 440
Chapter 13 441
Chapter 14 443
Index 445
Other Books You May Enjoy 466
Download
Rutracker.org не распространяет и не хранит электронные версии произведений, а лишь предоставляет доступ к создаваемому пользователями каталогу ссылок на торрент-файлы, которые содержат только списки хеш-сумм
Как скачивать? (для скачивания .torrent файлов необходима регистрация)
[Профиль]  [ЛС] 
 
Ответить
Loading...
Error