Clean Code Principles And Patterns
Clean Code Principles And Patterns
A Software Practitioner's Handbook
About the Book
Clean Code Principles and Patterns is one of the most comprehensive no-fluff guides for software developers to help them write clean code every day. The author Petri Silén has almost 30 years of industry experience in designing and implementing software, and now he puts all his knowledge gained during the years into this book. The book is packed with principles and patterns that help developers, from novices and juniors to seniors and experts, to write cleaner code. The principles and patterns presented in the book are accompanied by realistic yet straightforward examples to help the reader to understand them better. Examples are written in Java, JavaScript/TypeScript, and C++. Most of the examples are directly applicable to other programming languages, too. The reader should have basic knowledge of one object-oriented programming language to get the full benefit from this book.
The book is divided into ten chapters:
- Architectural design principles
- Object-oriented design principles
- Coding principles
- Testing principles
- Security principles
- API design principles
- Database types and related principles
- Concurrent programming principles
- Teamwork principles
- DevSecOps
After reading this book, you will know the following and much more:
- How to design modern cloud-native microservices
- What are autopilot microservices
- What are event sourcing, CQRS, distributed transactions, saga orchestration pattern, and saga choreography pattern
- What are the five SOLID principles, and how to put them into use in real-life code
- What are the 25 design patterns, and how to use them
- What is the MVC pattern, and how MVP and MVVM differ from each other
- How to achieve a clean design for a microservice
- Why and how to use dependency injection
- Detailed instructions with concrete examples on how to uniformly name various software entities like classes, functions, and variables
- Why you should prefer composition over inheritance
- How to split a software system into domains using domain-driven design
- How to organize a source code repository
- How to organize code into directories
- Concrete ways how to avoid writing comments and refactor comments away
- What are the most common issues that static code analyzers find, and how to correct them
- Most important refactoring techniques for everyday use
- Why you should use a statically typed language
- How to correctly handle errors and exceptions
- How to not forget handle errors and exceptions
- Why you should never pass or return a null value
- How to avoid off-by-one errors effectively
- What you should remember when using a Google search to get answers
- When and how to optimize code
- TDD, Unit testing, mocking, integration testing, E2E testing, and non-functional testing
- What is threat modeling and how to conduct it
- Authentication and authorization using OpenID Connect and OAuth2
- What are the essential security features to implement in an application
- How to design APIs using technologies like JSON-RPC, REST, GraphQL, SSE, WebSocket, gRPC, and event-driven services
- When and how to use a relational database, document database, key-value store, or wide-column database
- How to avoid SQL injection attacks using ORM or parameterized SQL queries
- When to use threading or parallel algorithms and how to ensure thread safety
- What principles to follow when working in a software development team
- What are DevOps, SecOps, and continuous integration (CI), and what is the difference between continuous delivery (CD) and continuous deployment (CD)
Table of Contents
- About the Author
- Introduction
- Architectural Principles
- Software Hierarchy
- Single Responsibility Principle
- Uniform Naming Principle
- Encapsulation Principle
- Service Aggregation Principle
- High Cohesion, Low Coupling Principle
- Library Composition Principle
- Avoid Duplication Principle
- Externalized Service Configuration Principle
- Environment Variables
- Kubernetes ConfigMaps
- Kubernetes Secrets
- Service Substitution Principle
- Inter-Service Communication Methods
- Synchronous Communication Method
- Asynchronous Communication Method
- Shared Data Communication Method
- Domain-Driven Architectural Design Principle
- Design Example 1: Mobile Telecom Network Analytics Software System
- Design Example 2: Banking Software System
- Autopilot Microservices Principle
- Stateless Microservices Principle
- Resilient Microservices Principle
- Horizontally Autoscaling Microservices Principle
- Highly-Available Microservices Principle
- Observable Microservices Principle
- Software Versioning Principles
- Use Semantic Versioning Principle
- Avoid Using 0.x Versions Principle
- Don’t Increase Major Version Principle
- Implement Security Patches and Bug Corrections to All Major Versions Principle
- Avoid Using Non-LTS Versions in Production Principle
- Git Version Control Principle
- Feature Branch
- Feature Toggle
- Architectural Patterns
- Event Sourcing Pattern
- Command Query Responsibility Segregation (CQRS) Pattern
- Distributed Transaction Patterns
- Saga Orchestration Pattern
- Saga Choreography Pattern
- Preferred Technology Stacks Principle
- Object-Oriented Design Principles
- SOLID Principles
- Single Responsibility Principle
- Open-Closed Principle
- Liskov’s Substitution Principle
- Interface Segregation and Multiple Inheritance Principle
- Program Against Interfaces Principle (Generalized Dependency Inversion Principle)
- Clean Microservice Design Principle
- Uniform Naming Principle
- Naming Interfaces and Classes
- Naming Functions
- Preposition in Function Name
- Example 1: Renaming JavaScript Array Methods
- Example 2: Renaming C++ Casting Expressions
- Naming Method Pairs
- Naming Boolean Functions (Predicates)
- Naming Builder Methods
- Naming Methods with Implicit Verbs
- Naming Property Getter Functions
- Naming Lifecycle Methods
- Naming Function Parameters
- Encapsulation Principle
- Immutable Objects
- Don’t Leak Modifiable Internal State Outside an Object Principle
- Don’t Assign From a Method Parameter to a Modifiable Field
- Real-life Example of Encapsulation Violation: React Class Component’s State
- Object Composition Principle
- Domain-Driven Design Principle
- Domain-Driven Design Example: Data Exporter Microservice
- Domain-Driven Design Example: Anomaly Detection Microservice
- Design Patterns
- Design Patterns for Creating Objects
- Factory Pattern
- Abstract Factory Pattern
- Factory Method Pattern
- Builder Pattern
- Singleton Pattern
- Prototype Pattern
- Object Pool Pattern
- Structural Design Patterns
- Composite Pattern
- Facade Pattern
- Bridge Pattern
- Strategy Pattern
- Adapter Pattern
- Proxy Pattern
- Decorator Pattern
- Flyweight Pattern
- Behavioral Design Patterns
- Chain of Responsibility Pattern
- Observer Pattern
- Command/Action Pattern
- Iterator Pattern
- State Pattern
- Mediator Pattern
- Template Method Pattern
- Memento Pattern
- Visitor Pattern
- Null Object Pattern
- Design Patterns for Creating Objects
- Don’t Ask, Tell Principle
- Law of Demeter
- Avoid Primitive Type Obsession Principle
- Dependency Injection (DI) Principle
- Avoid Code Duplication Principle
- Inheritance in Cascading Style Sheets (CSS)
- SOLID Principles
- Coding Principles
- Uniform Variable Naming Principle
- Naming Integer Variables
- Naming Floating-Point Number Variables
- Naming Boolean Variables
- Naming String Variables
- Naming Enum Variables
- Naming Collection (Array, List, and Set) Variables
- Naming Map Variables
- Naming Pair and Tuple Variables
- Naming Object Variables
- Naming Optional Variables
- Naming Function Variables (Callbacks)
- Naming Class Properties
- General Naming Rules
- Use Short, Common Names
- Pick One Name And Use It Consistently
- Avoid Obscure Abbreviations
- Avoid Too Short Or Meaningless Names
- Uniform Source Code Repository Structure Principle
- Java Source Code Repository Structure
- C++ Source Code Repository Structure
- JavaScript/TypeScript Source Code Repository Structure
- Domain-Based Source Code Structure Principle
- Avoid Comments Principle
- Name Things Properly
- Single Return Of Named Value At The End Of Function
- Return Type Aliasing
- Extract Constant for Boolean Expression
- Extract Named Constant or Enumerated Type
- Extract Function
- Name Anonymous Function
- Avoiding Comments in Bash Shell Scripts
- Function Single Return Principle
- Prefer a Statically Typed Language for Production Code Principle
- Function Arguments Might Be Given in Wrong Order
- Function Argument Might Be Given with Wrong Type
- Not All Function Arguments Are Given
- Function Return Value Type Might Be Misunderstood
- Forced to Write Public API Comments
- Type Errors Are Not Found in Testing
- Refactoring Principle
- Rename
- Extract Method
- Extract Constant
- Replace Conditionals with Polymorphism
- Introduce Parameter Object
- Invert If Statement
- Static Code Analysis Principle
- Common Static Code Analysis Issues
- Error/Exception Handling Principle
- Handling Checked Exceptions in Java
- Returning Errors
- Returning Failure Indicator
- Returning an Optional Value
- Returning an Error Object
- Adapt to Wanted Error Handling Mechanism
- Asynchronous Function Error Handling
- Functional Exception Handling
- Stream Error Handling
- Don’t Pass or Return Null Principle
- Avoid Off-By-One Errors Principle
- Be Critical When Googling Principle
- Optimization Principle
- Optimization Patterns
- Optimize Busy Loops Only Pattern
- Remove Unnecessary Functionality Pattern
- Copy Memory in Chunks Pattern (C++)
- Object Pool Pattern
- Replace Virtual Methods with Non-Virtual Methods Pattern (C++)
- Inline Methods Pattern (C++)
- Use Unique Pointer Pattern (C++)
- Share Identical Objects a.k.a Flyweight Pattern
- Optimization Patterns
- Uniform Variable Naming Principle
- Testing Principles
- Functional Testing Principles
- Unit Testing Principle
- Test-Driven Development (TDD)
- Naming Conventions
- Mocking
- UI Component Unit Testing
- Software Component Integration Testing Principle
- UI Integration Testing
- Setting Up Integration Testing Environment
- End-to-End (E2E) Testing Principle
- Unit Testing Principle
- Non-Functional Testing Principle
- Performance Testing
- Data Volume Testing
- Stability Testing
- Reliability Testing
- Stress and Scalability Testing
- Security Testing
- Other Non-Functional Testing
- Functional Testing Principles
- Security First Principle
- Threat Modelling
- Decompose Application
- Determine and Rank Threats
- Determine Countermeasures and Mitigation
- Security Features
- Authentication and Authorization
- OpenID Connect Authentication and Authorization in Frontend
- OAuth2 Authorization in Backend
- Password Policy
- Cryptography
- Denial-of-service (DoS) Prevention
- SQL Injection Prevention
- Security Configuration
- Automatic Vulnerability Scanning
- Integrity
- Error Handling
- Audit Logging
- Input Validation
- Validating Numbers
- Validating Strings
- Validating Arrays
- Validating Objects
- Validation Library Example
- Authentication and Authorization
- Threat Modelling
- API Design Principles
- Frontend Facing API Design Principles
- JSON-RPC API Design Principle
- REST API Design Principle
- Creating a Resource
- Reading Resources
- Updating Resources
- Deleting Resources
- Executing Non-CRUD Actions on Resources
- Resource Composition
- HTTP Status Codes
- HATEOAS and HAL
- Versioning
- Documentation
- Implementation Example
- GraphQL API Design
- Subscription-Based API Design
- Server-Sent Events (SSE)
- GraphQL Subscriptions
- WebSocket Example
- Inter-Microservice API Design Principles
- Synchronous API Design Principle
- Asynchronous API Design Principle
- Request-Only Asynchronous API Design
- Request-Response Asynchronous API Design
- Frontend Facing API Design Principles
- Databases And Database Principles
- Relational Databases
- Structure of Relational Database
- Use Object Relational Mapper (ORM) Principle
- Entity/Table Relationships
- One-To-One/Many Relationships
- Many-To-Many Relationships
- Use Parameterized SQL Statements Principle
- Normalization Rules
- First Normal Form (1NF)
- Second Normal Form (2NF)
- Third Normal Form (3NF)
- Document Database Principle
- Key-Value Database Principle
- Wide-Column Database Principle
- Search Engine Principle
- Relational Databases
- Concurrent Programming Principles
- Threading Principle
- Parallel Algorithms
- Thread Safety Principle
- Synchronization Directive
- Atomic Variables
- Concurrent Collections
- Mutexes
- Spinlocks
- Threading Principle
- Teamwork Principles
- Use Agile Framework Principle
- Define the Done Principle
- You Write Code for Other People Principle
- Avoid Technical Debt Principle
- Software Component Documentation Principle
- Code Review Principle
- Focus on Object-Oriented Design
- Focus on Proper and Uniform Naming
- Don’t Focus on Premature Optimization
- Detect Possible Malicious Code
- Uniform Code Formatting Principle
- Highly Concurrent Development Principle
- Dedicated Microservices and Microlibraries
- Dedicated Domains
- Follow Open-Closed Principle
- Pair Programming Principle
- Well-Defined Development Team Roles Principle
- Product Owner
- Scrum Master
- Software Developer
- Test Automation Developer
- DevOps Engineer
- UI Designer
- DevSecOps
- SecOps Lifecycle
- DevOps Lifecycle
- Plan
- Code
- Build and Test
- Release
- Example Dockerfile
- Example Kubernetes Deployment
- Example CI/CD Pipeline
- Deploy
- Operate
- Monitor
- Logging
- OpenTelemetry Log Data Model
- PrometheusRule Example
- Appendix A
The Leanpub 60-day 100% Happiness Guarantee
Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.
See full terms
80% Royalties. Earn $16 on a $20 book.
We pay 80% royalties. That's not a typo: you earn $16 on a $20 sale. If we sell 5000 non-refunded copies of your book or course for $20, you'll earn $80,000.
(Yes, some authors have already earned much more than that on Leanpub.)
In fact, authors have earnedover $12 millionwriting, publishing and selling on Leanpub.
Learn more about writing on Leanpub
Free Updates. DRM Free.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).
Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.
Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.
Learn more about Leanpub's ebook formats and where to read them