Crafting Clean Code with JavaScript and React: A Practical Guide to Sustainable Front-End Development

Crafting Clean Code with JavaScript and React: A Practical Guide to Sustainable Front-End Development

Crafting Clean Code with JavaScript and React: A Practical Guide to Sustainable Front-End Development
Автор: Khalfallah Héla Ben
Дата выхода: 2024
Издательство: Apress Media, LLC.
Количество страниц: 443
Размер файла: 6.7 MB
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы

Table of Contents....5

About the Author....11

About the Technical Reviewer....12

Introduction: The JavaScript Bubbling Movement....13

Chapter 1: Getting Started: Presenting the Context....16

The Team....17

The Web Application....18

Nonfunctional and Technical Requirements....20

Nonfunctional Requirements....20

Technical Requirements....21

Conclusion....22

Chapter 2: Functional Programming: Blueprint for Pure Code....23

JavaScript Against Others....24

Elm: A Deep Dive....27

ReasonML: An Overview....32

Emscripten: An In-Depth Look....34

TypeScript: An In-Depth Look....36

The Decision: JavaScript....38

The Rise of Functional Programming....39

JavaScript Paradigms....39

Foundations of Functional Thinking....40

Code Driven by Composition....40

Side Effects....42

Pure Functions: The Bedrock of Predictable Code....49

Defining Purity....50

Why Pure Functions Matter....50

Pure vs. Impure: A JavaScript Perspective....51

Pure Functions in React....51

Real-World Applications....52

Mathematical Notation....52

Key Takeaways....54

Immutable and Scoped Variables and Parameters....54

What Makes Immutability So Significant?....54

Primitive and Reference Data Types....55

Deep vs. Shallow Copy: Understanding Object Duplication in JavaScript....58

Declarative Approach to Reduce Code Amount....61

Declarative vs. Imperative....61

Generalizing with Higher-Order Functions....62

Abstraction, Modularity, and Function Composition....63

Handling Code Complexity: Split, Compose, and Reuse....64

The Power of Composition....65

Composition in JavaScript....65

Benefits of Composition....66

Higher-Order Functions: The Glue of Composition....66

Currying: Simplifying Functions with Partial Application....67

Benefits of Currying....68

Beyond Unit Conversion....68

Key Takeaways....69

Functional Programming Superpowers....69

Memoization....69

Why Memoization?....70

Requirements for Memoization....70

Memoization in JavaScript....70

Recursion....72

Memoization and Recursion....81

Lazy Evaluation: Optimizing Computation Through Demand-Driven Execution....84

Functors: Composable Transformations in a Safe Context....85

Monads: Elevating Functional Programming....87

Key Takeaways....89

Thinking Functionally with JavaScript....90

Scoped Variables: let and const....90

Key Takeaways....93

Arrow Functions....94

Key Takeaways....98

High-Order Functions: The Basic Unit of Abstraction....98

Creating Our Own Control Abstractions....102

map to Transform Array Data....103

reduce to Group Array Results....109

filter Out Undesirable Elements....110

Chaining: Performing Sequential Operations on Arrays....111

every/some....112

Time and Space Complexity of JavaScript Array Methods....114

Key Takeaways....116

Metaprogramming in JavaScript....117

Proxies....117

Reflection....118

Use Cases for Proxies and Reflection....119

Validation....119

Logging and Profiling....120

Immutability....121

Dynamic Object Composition....122

Security....123

Cautions with Metaprogramming....124

Debugging....124

Performance....124

Security....124

Creating Shallow Copy with Spread....124

Optional Chaining with “OR”: Safe Access with Default Values....132

Maybe: “If (Not Null) Then” As an Expression....137

The Problem with Null Checks....137

The Maybe Solution....138

Benefits....139

Either: "If/Else" As an Expression....139

The Problem with Traditional Error Handling....139

The Either Solution....140

Example: Error Handling in a Division Function....141

Example: Handling HTTP Response....142

Benefits....144

Pattern Matching: switch As an Expression....145

Key Takeaways....146

Thinking Functionally About UI Using ReactJS....147

React Declarative Approach....147

Lazy Evaluation....151

Memoization....152

Lazy Loading....155

Higher-Order Component (HOC)....157

Effects....160

Functional Reactive Programming (FRP) in React....162

Key Takeaways....164

Thinking Functionally About Async Side Effects....165

Asynchrony Jargon....166

Promisification....168

Linear Async Flows....174

Generators....174

Generator: Early Completion....178

Generator: Early Abort....181

An Attempt to Make Asynchronous Generators....183

Asynchronous Generators....192

Key Takeaways....199

Conclusion....200

Chapter 3: SAGE(S)-Driven Design: An Inclusive and Eco-friendly Website....201

SAGE(S)-Driven Design....202

Semantic....203

Reviving the Power of HTML....203

Backbone of an HTML Document....206

Order and Priority of Web Resource Loads....209

Body’s Arrangement....210

HTML Elements Categories....210

Break the Page into Sections....211

Root Layout....212

The Dilemma: Article vs. Section....213

Headings Hierarchy....214

Paragraph....215

Text-Level Semantics....215

How Can a List of Data Be Represented in a Semantic Way?....217

How to Semantically Organize a Form?....217

Semantic Media Elements....219

Layout Validation....220

Key Takeaways....220

Accessible....221

What Does It Mean to Be “Accessible”?....221

Accessibility Guidelines....222

Screen Readers and HTML....223

Temporary Disabilities....224

Accessibility Best Practices....224

WAI-ARIA....225

Accessibility Testing Tools....227

Key Takeaways....228

Green....229

Sustainable UX Design....229

Sustainable UX Design Practices....230

Easy (KISS): Keep It Simple, Stupid....231

KISS UI/UX Design....231

KISS Software Development....232

Key Takeaways....232

Secure....233

Frontend Security Threats....233

URL-Based Attacks....234

DOM-Based Attacks....235

Form-Based Attacks....237

Input Attacks....237

Form Action Hijacking....238

JSON-Based Attacks....239

React Escape Hatches....240

Dependencies Vulnerabilities....242

Defense Plans....242

Prevent URL-Based XSS Attacks....242

Prevent DOM-Based XSS Attacks....243

innerText Instead of innerHTML....243

Prevent Form-Based XSS Attacks....244

Prevent Dependencies Vulnerabilities....244

Key Takeaways....245

Conclusion....246

Chapter 4: HOFA: The Path Toward Clean Architecture....247

Why Does Software Design and Architecture Matter?....248

Foundation and Plan....248

Team Collaboration....248

Consistency and Automation....248

Adaptive Architecture....249

Bugs and Regressions....249

Quality and Future-Proofing....249

“Good” Architecture’s Definition....249

Learnability....251

Performance (Time and Resource Utilization)....252

Configurability....252

Flexibility....252

Testability....253

Maintainability....253

Measuring Architecture Characteristics....253

Mathematical Model for Software Architecture (Sets and Graphs)....253

Sets for Describing Modules....254

Graphs for Visualizing Relationships....254

Sets for Measuring Cohesion....254

Graphs for Measuring Coupling....255

Benefits of This Approach....256

Practical Measurement of Software Architecture's Effectiveness....256

Metrics....256

Efferent Coupling (CE)....258

Afferent Coupling (CA)....258

Instability Index....259

Code Health Meter Tool....260

Frontend-Oriented Architecture Styles....261

Atomic Design....261

Unidirectional Architecture....267

Extending Capabilities with Ports and Adapters (Hexagonal Architecture)....275

Defining Subdomains (Feature-Sliced Design)....280

Reinforcing Boundaries (Onion Architecture)....282

Final Architecture: HOFA Architecture....289

Merge Patterns and Maximize Profits....290

Benefits....295

Trade-Offs....297

Key Takeaways....298

Conclusion....301

Chapter 5: MOME: Befriend User Execution Capabilities....302

Why Does Performance Matter?....302

What Factors Can Impact Both Loading and Interaction Performance?....303

Browser Internal Working....303

Focus on the Rendering Engine....307

Interaction Between Rendering Engine and JavaScript....310

The Order of Processing Scripts and Stylesheets....312

JavaScript Engines Working Pipeline....316

Standard Working Pipeline for JavaScript Engine....316

V8 (Chrome) Pipeline....318

SpiderMonkey (Firefox) Pipeline....321

Executing an Asynchronous Task (Case of V8)....323

Memory Management (Case of V8)....326

Lessons Learned....327

“MOME” Performance Methodology....330

Measure....330

Performance Metrics....330

A Metric for Each Phase....330

First Contentful Paint....332

Largest Contentful Paint (LCP)....333

First Input Delay (FID)....334

Cumulative Layout Shift (CLS)....335

Interaction to Next Paint (INP)....336

Core Web Vitals....338

Time to Interactive (TTI)....339

Total Blocking Time (TBT)....341

Performance Measurement Tools....343

Code Coverage (Find Unused JavaScript and CSS)....343

Performance Monitor (Analyze Runtime Performance)....345

Network Monitor (Inspect Network Activity)....347

Memory Inspection (Find Memory Issues)....349

Lighthouse (All in One)....351

WebPageTest (Beyond the Local)....353

HTTP Archive (Keep an Eye on the World)....355

Optimize....356

Lazy-First....356

Small Is Better....360

Modern Is More Efficient....362

Adaptive Serving....363

Other Tips....365

Monitor....366

Performance Budgets (Catch Issues Before They Ship)....366

Project Health Tool....369

Educate....371

Key Takeaways....371

Conclusion....373

Chapter 6: CRISP: Clean, Reliable, Integrated Software Process....374

Why CRISP?....375

Pre-development....376

Define a Common Development Protocol....376

Naming Convention....376

Import Order....381

Self-documenting Code vs. Comments....381

Define a Shared Checklist....384

React Checklist....384

W3C Compliance Checklist....386

A11Y Checklist....388

Performances Checklist....392

Security Checklist....393

Browser Compatibility....396

First Step Toward Automated Best Practices....397

Code Generator....397

ESLint for Code-Level Analysis....398

Complexity Analysis....398

Adherence to JavaScript Recommendations....399

Modern JavaScript Features....399

Integrating the Airbnb JavaScript Style Guide....400

Code Formatting....400

Code Health Meter....401

Cognitive Complexity: A Subjective Lens on Code Readability....402

Limitations of Cognitive Complexity....402

Why I Don’t Rely on Cognitive Complexity....403

Bundle Analysis....403

Dependency Management....404

During Development....406

The World of Testing....406

Testing Trophy: A Balanced Approach to Modern Software Testing....406

Unit Testing Reusable Components....408

Integration Testing with Cypress....412

End-to-End Testing with Cypress....413

Visual Testing....414

Why Visual Testing Matters?....414

Visual Testing with Puppeteer and Pixelmatch....415

Key Takeaways: Building a Robust Testing Strategy for React....417

Essential DevTools for React Development: Mastering Our Toolkit....419

React Developer Tools: Our Window into the React World....419

Browser Developer Tools: Our Web Development Arsenal....420

Proactive Use of DevTools....421

Documentation: Empowering Collaboration and Understanding....422

Types of Documentation: Meeting Diverse Needs....422

Best Practices for Documentation Excellence....423

Reaping the Rewards: Why Documentation Matters....424

Overcoming Challenges....424

Post-development....425

Collaborative Coding: Powering React Development with Teamwork....425

Key Collaborative Practices....425

Pull Requests (PRs) and Release Flow: Bridging Collaboration and Delivery....426

Collaborative Coding in the React Ecosystem....427

Continuous Integration (CI): Our Safety Net for Code Quality....428

Automated Code Verification....429

Automated Bundle Check and Security Scanning....430

GitLab CI/CD Example....432

The Power of Continuous Integration and Automated Verification....433

Project Health Tool (phTool)....433

Monitoring and Logging: Keeping Your React Apps Healthy....436

Application Monitoring: The Pulse of Your App....436

Error Logging: Your Application’s Black Box....437

Best Practices for Monitoring and Logging....438

Key Takeaways....439

Conclusion....440

Book Summary....441

Understand the guiding principles of “clean code” and how it applies to modern front-end development, accessibility (a11y), semantics, performance, and the Green Web. Highlighting key topics ranging from the foundations of JavaScript and HTML to popular frameworks like React, this book provides best practices to ensure code and applications are easier, more efficient and cost effective to run.

Using a web-based application as an example, you’ll begin by cleaning and improving its code base by dividing the JavaScript into smaller, reusable and composable functions without side effects. Then, you’ll improve the HTML code base by applying "Disability Driven Design" patterns, focusing on semantics before moving on to improving the architecture with a functional style (immutable, modular and composable).

Because the web today needs to be green with reduced loading time and energy consumption, you’ll apply some tips and tricks to improve code performance and see how to best monitor it in a continuous and scalable way.

What You’ll Learn

  • See how the JavaScript engine works and memory management.
  • Explore in greater detail key focus areas of accessibility and green computing
  • Make applications easier and more cost-effective to run
  • Look closely at clean and sustainable development using JavaScript and React

Who This Book Is For

Programmers, developers, engineers and product managers who are looking at cost-efficient ways to make their applications run more smoothly and efficiently.


Похожее:

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

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