от библиотек на C++/Rust до распределённых кластеровfrom C++/Rust libraries to distributed clusters

Архитектура, принципы проектирования и парадигмыArchitecture, design principles & paradigms

Единый понятийный аппарат для систем любой сложности: SOLID, паттерны проектирования GoF, DDD и гексагональная/чистая архитектура (как структурировать одно приложение), прагматичные философии простоты (KISS/DRY/YAGNI/AHA), правила проектирования API, принципы Дяди Боба для пакетов, архитектура данных и распределённых систем, 12-Factor App. 7 подразделов, 41 пункт: 12.1 SOLID заполнен (5 страниц), остальные — каркас.A unified conceptual toolkit for systems of any complexity: SOLID, GoF design patterns, DDD and hexagonal/clean architecture (how to structure a single application), pragmatic simplicity philosophies (KISS/DRY/YAGNI/AHA), API design rules, Uncle Bob's package principles, data & distributed-systems architecture, the 12-Factor App. 7 subsections, 41 items: 12.1 SOLID is filled in (5 pages), the rest are skeletons.

12.1 Принципы SOLID12.1 The SOLID principles

12.1.1 Single Responsibility (SRP)у модуля должна быть только одна причина для изменения — высокая связность (High Cohesion), без смешения бизнес-логики, персистентности и представления.a module should have only one reason to change — high cohesion, no mixing of business logic, persistence, and presentation.interview 12.1.2 Open/Closed (OCP)открыт для расширения, закрыт для модификации — новый функционал через новые классы и полиморфизм, а не переписывание проверенного кода.open for extension, closed for modification — new functionality via new classes and polymorphism, not rewriting tested code.interview 12.1.3 Liskov Substitution (LSP)подтип должен подставляться вместо базового типа без изменения корректности — Design by Contract, наследник не ослабляет пост-условия и не усиливает пре-условия.a subtype must be substitutable for its base type without breaking correctness — Design by Contract, a subclass may not weaken postconditions or strengthen preconditions.interview 12.1.4 Interface Segregation (ISP)клиенты не должны зависеть от методов, которые не используют — дробление «толстых» интерфейсов на узкоспециализированные.clients shouldn't depend on methods they don't use — splitting "fat" interfaces into narrow, specialized ones.interview 12.1.5 Dependency Inversion (DIP)модули верхнего и нижнего уровня зависят от абстракций, а не друг от друга — разрыв жёстких связей через Dependency Injection и IoC.high-level and low-level modules both depend on abstractions, not on each other — decoupling via dependency injection and IoC.interview

12.2 Паттерны проектирования GoF12.2 GoF design patterns

новый подраздел — каркасnew subsection — skeleton
12.2.1 Порождающие паттерныCreational patternsFactory Method, Abstract Factory, Builder, Prototype, Singleton — разделение «как создан объект» от «что он делает», и почему Singleton чаще всего оказывается антипаттерном на практике.Factory Method, Abstract Factory, Builder, Prototype, Singleton — separating "how an object is created" from "what it does", and why Singleton usually turns out to be an anti-pattern in practice.interview 12.2.2 Структурные паттерныStructural patternsAdapter, Decorator, Facade, Proxy, Composite — компоновка объектов в более крупные структуры без изменения их кода; связь Decorator с Open/Closed (12.1.2).Adapter, Decorator, Facade, Proxy, Composite — composing objects into larger structures without changing their code; Decorator's connection to Open/Closed (12.1.2).interview 12.2.3 Поведенческие паттерныBehavioral patternsStrategy, Observer, Command, Iterator, State, Template Method, Visitor — как распределить обязанности и коммуникацию между объектами; Strategy как объектно-ориентированная альтернатива switch по типу.Strategy, Observer, Command, Iterator, State, Template Method, Visitor — distributing responsibility and communication between objects; Strategy as an object-oriented alternative to a switch on type.interview 12.2.4 АнтипаттерныAnti-patternsGod Object, Spaghetti Code, Golden Hammer (применение знакомого паттерна не по месту) — паттерн, применённый там, где он не нужен, сам становится источником случайной сложности.God Object, Spaghetti Code, the Golden Hammer (applying a familiar pattern where it doesn't fit) — a pattern applied where it isn't needed becomes a source of accidental complexity itself.

12.3 DDD и гексагональная архитектура12.3 DDD & hexagonal architecture

новый подраздел — как структурировать одно приложениеnew subsection — how to structure a single application
12.3.1 Building blocks предметно-ориентированного проектированияDomain-driven design building blocksEntity, Value Object, Aggregate (и Aggregate Root как единственная точка входа для изменений), Repository, Domain Event — словарь DDD и то, какую проблему согласованности решает каждый термин.Entity, Value Object, Aggregate (with the Aggregate Root as the single entry point for changes), Repository, Domain Event — the DDD vocabulary and which consistency problem each term solves.interview 12.3.2 Bounded Context и стратегическое проектированиеBounded contexts & strategic designBounded Context как граница применимости модели, Context Mapping (Shared Kernel, Anti-Corruption Layer, Customer-Supplier) — почему одно и то же слово («заказ») может законно означать разное в разных частях системы.the Bounded Context as a model's boundary of applicability, Context Mapping (Shared Kernel, Anti-Corruption Layer, Customer-Supplier) — why the same word ("order") can legitimately mean different things in different parts of a system. 12.3.3 Гексагональная архитектура (Ports & Adapters)Hexagonal architecture (Ports & Adapters)Домен в центре, порты как интерфейсы, адаптеры как реализации для конкретной инфраструктуры (БД, HTTP, очередь) — прямое применение Dependency Inversion (12.1.5) на уровне архитектуры целого приложения.the domain at the center, ports as interfaces, adapters as implementations for specific infrastructure (DB, HTTP, queue) — Dependency Inversion (12.1.5) applied directly at the whole-application architecture level.interview 12.3.4 Clean/Onion ArchitectureClean/Onion architectureКонцентрические слои с зависимостями строго внутрь (Dependency Rule) — чем гексагональная архитектура, Clean Architecture (Дядя Боб) и Onion Architecture по сути один и тот же принцип под разными именами, а чем различаются.concentric layers with dependencies pointing strictly inward (the Dependency Rule) — how hexagonal architecture, Clean Architecture (Uncle Bob), and Onion Architecture are at heart the same principle under different names, and where they differ.

12.4 Философии простоты и прагматизма12.4 Simplicity & pragmatism philosophies

против случайной сложности и overengineeringagainst accidental complexity and overengineering
12.4.1 KISSмаксимальная простота реализации как главный приоритет — сложность порождает баги, дыры в безопасности и задержки.maximum implementation simplicity as the top priority — complexity is the main source of bugs, security holes, and latency.interview 12.4.2 DRY и& WETисключение дублирования знаний — каждая концепция должна иметь единственное недвусмысленное представление в системе.eliminating duplicated knowledge — every concept should have a single, unambiguous representation in the system.interview 12.4.3 YAGNIне реализовывать функционал, который не нужен прямо сейчас — защита от преждевременного абстрагирования под гипотетическое будущее.don't implement functionality the system doesn't need right now — a guard against premature abstraction for a hypothetical future.interview 12.4.4 AHAбаланс против слепого DRY — лучше допустить 2-3 раза дублирование, чем создать неверную абстракцию, от которой потом сложно избавиться.a counterweight to blind DRY — better to tolerate duplication 2-3 times than lock in a wrong abstraction that's hard to undo later.

12.5 Проектирование модулей и API12.5 Module & API design

12.6 Принципы пакетного связывания (Uncle Bob)12.6 Package principles (Uncle Bob)

связность и зацепление компонентовcomponent cohesion & coupling
12.6.1 REPRelease/Reuse Equivalency — граница повторного использования совпадает с границей релиза, компонент чётко версионирован. — the reuse boundary matches the release boundary, the component is clearly versioned. 12.6.2 CCPCommon Closure — классы, меняющиеся по одной причине, объединяются в один компонент (аналог SRP для пакетов). — classes that change for the same reason belong in the same component (SRP's analogue for packages). 12.6.3 CRPCommon Reuse — классы одного компонента используются совместно; пользователь не зависит от ненужных ему классов (аналог ISP для пакетов). — classes in one component are used together; a consumer doesn't depend on classes it doesn't need (ISP's analogue for packages). 12.6.4 ADPAcyclic Dependencies — в графе зависимостей между компонентами не должно быть циклов. — no cycles allowed in the component dependency graph.interview 12.6.5 SDPStable Dependencies — зависимости направлены в сторону стабильности, модуль зависит только от более стабильных модулей. — dependencies point toward stability, a module depends only on more stable modules. 12.6.6 SAPStable Abstractions — стабильный компонент должен быть абстрактным (интерфейсы), нестабильный — конкретным. — a stable component should be abstract (interfaces), an unstable one concrete.

12.7 Архитектура данных, распределённых систем и облака12.7 Data, distributed-systems & cloud architecture

CQRS, CAP/PACELC, Event Sourcing, 12-Factor App
12.7.1 CQRSCommand Query Responsibility Segregation — разделение моделей чтения и записи на уровне архитектуры для оптимизации нагрузки. — separating read and write models at the architecture level to optimize load.interview 12.7.2 CAP и& PACELCпри сетевом расщеплении выбор между Consistency и Availability; PACELC добавляет выбор между Latency и Consistency, когда расщепления нет.under a network partition, choose between Consistency and Availability; PACELC adds a Latency-vs-Consistency choice when there's no partition.interview 12.7.3 Event Sourcingсостояние системы определяется неизменяемой последовательностью событий, а не текущей строкой в БД.system state is defined by an immutable sequence of events rather than a current row in the database. 12.7.4 12-Factor I: Codebaseодна кодовая база в VCS, множество развёртываний.one codebase tracked in VCS, many deploys. 12.7.5 12-Factor II: Dependenciesявно объявленные и изолированные зависимости, без системных библиотек «по умолчанию».explicitly declared and isolated dependencies, no reliance on system-wide packages. 12.7.6 12-Factor III: Configконфигурация хранится в переменных окружения, а не в коде.configuration lives in environment variables, not in code.interview 12.7.7 12-Factor IV: Backing ServicesБД и очереди — подключаемые ресурсы (Attached Resources), заменяемые без изменения кода.databases and queues are attached resources, swappable without changing code. 12.7.8 12-Factor V: Build, Release, Runстрогое разделение стадий сборки, релиза и выполнения.strict separation of the build, release, and run stages. 12.7.9 12-Factor VI: Processesприложение — один или несколько процессов без сохранения состояния (stateless / share-nothing).the app runs as one or more stateless, share-nothing processes.interview 12.7.10 12-Factor VII: Port Bindingсервис самодостаточен и экспортируется через привязку к порту.the service is self-contained and exports itself via port binding. 12.7.11 12-Factor VIII: Concurrencyмасштабирование через горизонтальное размножение процессов (process model), а не потоков внутри одного процесса.scaling via horizontal process replication (the process model), not threads inside one process. 12.7.12 12-Factor IX: Disposabilityбыстрый запуск и graceful shutdown по SIGTERM.fast startup and graceful shutdown on SIGTERM.interview 12.7.13 12-Factor X: Dev/Prod Parityмаксимальная схожесть окружений разработки, staging и продакшена.development, staging, and production environments stay as similar as possible. 12.7.14 12-Factor XI: Logsлоги — потоки событий в stdout/stderr, а не файлы, которыми управляет само приложение.logs are event streams to stdout/stderr, not files the app manages itself. 12.7.15 12-Factor XII: Admin Processesадминские и миграционные задачи запускаются в том же окружении, что и основной процесс.admin/migration tasks run in the same environment as the main process.

статус и связь с остальной базойstatus & relation to the rest of the KB

12.1 SOLID заполнен — 5 полных страниц (SRP, OCP, LSP, ISP, DIP) с примерами на C++/Rust и разбором типичных ошибок применения каждого принципа. Добавлены два подраздела, отсутствовавшие в исходном плане, несмотря на заявленную полноту раздела: 12.2 «Паттерны GoF» (порождающие/структурные/поведенческие плюс антипаттерны) и 12.3 «DDD и гексагональная архитектура» — уровень «как структурировать одно приложение», отсутствовавший между принципами (12.1) и распределённо-облачными паттернами (бывший 12.5, теперь 12.7). Остальные подразделы сдвинуты по нумерации: прагматизм → 12.4, API-дизайн → 12.5, пакетные принципы Дяди Боба → 12.6, данные/распределённые системы/12-Factor → 12.7. Все, кроме 12.1, остаются каркасом. Метка interview отмечает пункты, которые чаще всего всплывают на технических собеседованиях.12.1 SOLID is filled in — 5 full pages (SRP, OCP, LSP, ISP, DIP) with C++/Rust examples and a breakdown of common misapplications of each principle. Two subsections missing from the original plan despite the section's claimed completeness were added: 12.2 "GoF patterns" (creational/structural/behavioral plus anti-patterns) and 12.3 "DDD & hexagonal architecture" — the "how to structure a single application" layer that was missing between the principles (12.1) and distributed/cloud patterns (formerly 12.5, now 12.7). The remaining subsections were renumbered: pragmatism → 12.4, API design → 12.5, Uncle Bob's package principles → 12.6, data/distributed systems/12-Factor → 12.7. Everything except 12.1 remains a skeleton. The interview tag marks the items that come up most often in technical interviews.