Установка
SKILL.md
A Philosophy of Software Design Framework
A practical framework for managing the fundamental challenge of software engineering: complexity. Apply these principles when designing modules, reviewing APIs, refactoring code, or advising on architecture decisions.
Core Principle
The greatest limitation in writing software is our ability to understand the systems we are creating. Complexity is the enemy: it makes systems hard to understand, hard to modify, and a source of bugs. Evaluate every design decision by asking "Does this increase or decrease the overall complexity of the system?" — the goal is not zero complexity, but minimizing unnecessary complexity and concentrating the necessary kind where it can be managed.
Scoring
Goal: 10/10. When reviewing or creating a design, score it by counting how many of the eight Quick Diagnostic rows it satisfies (≈1.25 points each), then sanity-check against the bands:
- 9-10 — deep modules with interfaces far simpler than implementations; no information leakage (an implementation can change without touching callers); interface comments capture design intent; design improvement is routine. All eight diagnostics pass.
- 6-8 — mostly deep, but one or two leaks, shallow classes, or undocumented abstractions. 5-6 diagnostics pass.
- 3-5 — classitis or temporal decomposition, recurring leakage, comments that only restate code. 2-4 diagnostics pass.
- ≤2 — tactical-tornado code: shallow modules, pervasive leakage, no design intent recorded. 0-1 diagnostics pass.
Always state the current score, the diagnostic rows that failed, and the specific change each one needs to reach 10/10.
The Software Design Framework
Six principles for managing complexity and producing systems that are easy to understand and modify:
1. Complexity and Its Causes
Core concept: Complexity is anything about a system's structure that makes it hard to understand and modify. It shows three symptoms — change amplification, cognitive load, and unknown unknowns — and has two causes: dependencies and obscurity.
Key insights:
- Change amplification: a simple change requires edits in many places
- Cognitive load: a developer must hold too much in mind to make a change
- Unknown unknowns: it isn't obvious what must change or what information is relevant — the worst symptom
- Complexity is incremental — it accumulates from hundreds of small decisions ("death by a thousand cuts"), so every decision matters
Code applications:
| Context | Pattern | Example |
|---|---|---|
| Change amplification | Centralize shared knowledge | Extract color constants instead of hardcoding #ff0000 in 20 files |
| Cognitive load | Reduce what developers must know | open(path) instead of requiring buffer size, encoding, lock mode |
| Unknown unknowns | Make dependencies explicit | Type systems and interfaces surface what a change affects |
| Obscurity | Name things precisely | numBytesReceived not n; retryDelayMs not delay |
See references/complexity-symptoms.md when you need to name which symptom a codebase has before fixing it — per-symptom recognition tests, the dependency taxonomy (syntactic/semantic/temporal/hidden), the C = Σ(cp·tp) cost formula, and a 10-row red-flag table.
2. Deep vs Shallow Modules
Core concept: The best modules are deep: powerful functionality behind a simple interface. Shallow modules have complex interfaces relative to the functionality they provide — they add complexity rather than hiding it.
Why it works: The interface is the cost a module imposes on the rest of the system; the implementation is the benefit. So a method that is harder to learn than to re-implement yourself is net-negative — depth, not line count, decides whether a module earns its place.
Key insights:
- Depth = functionality provided / interface complexity imposed (Unix file I/O is deep; thin Java I/O wrappers are shallow)
- "Classitis": the disease of creating too many small, shallow classes — each interface adds cognitive load
- Small methods are not inherently good; depth matters more than size
- The best abstractions hide significant complexity behind a few simple concepts
Code applications:
| Context | Pattern | Example |
|---|---|---|
| Deep module | Hide complexity behind simple API | file.read(path) hides disk blocks, caching, buffering, encoding |
| Classitis cure | Merge related shallow classes | RequestParser + RequestValidator + RequestProcessor → one RequestHandler |
| Interface simplicity | Fewer parameters, fewer methods | config.get(key) with sensible defaults, not 15 constructor parameters |
See references/deep-modules.md when judging whether an abstraction pulls its weight — before/after code for the depth ratio, the classitis cure worked out, and case studies (Unix I/O, GC, TCP/IP).
3. Information Hiding and Leakage
Core concept: Each module should encapsulate knowledge not needed by other modules. Information leakage — one design decision reflected in multiple modules — is one of the most important red flags in software design.
Why it works: A decision that lives in one module can change there and nowhere else; the same decision leaked into N modules turns one edit into N edits that no compiler will remind you to make. Hiding is what converts change amplification back into a local change.
Key insights:
- Temporal decomposition causes leakage: splitting code by when things happen forces shared knowledge across phases — organize by knowledge instead
- Back-door leakage through data formats, protocols, or shared assumptions is the subtlest form
- Decorators frequently leak — they expose the decorated interface
- If two modules share knowledge, merge them or create a new module that encapsulates it
Code applications:
| Context | Pattern | Example |
|---|---|---|
| Format leakage | Centralize serialization | One module owns JSON encoding/decoding, not json.dumps everywhere |
| Temporal decomposition | Organize by knowledge, not time | Combine "read config" and "apply config" into one config module |
| Protocol leakage | Abstract transport details | MessageBus.send(event) hides HTTP vs. gRPC vs. queue |
See references/information-hiding.md when a change forces you to edit two modules in lockstep — the four leakage forms with code (interface, back-door, temporal, decorator), five reduction strategies, the HTTP-handling case study, and a detection table.
4. General-Purpose vs Special-Purpose Modules
Core concept: Design modules that are "somewhat general-purpose": an interface general enough to support multiple uses, with an implementation that handles current needs. Ask: "What is the simplest interface that will cover all my current needs?"
Why it works: Counterintuitively, the general interface is usually the simpler one — special-case methods multiply as requirements grow, while one general method absorbs them. The trap is the other direction: generality the current needs don't demand is speculative complexity, paid now for a use case that may never arrive.
Key insights:
- "Somewhat general-purpose" is the sweet spot between too specific and too generic
- Push complexity downward: lower-level modules should handle hard cases so upper levels stay simple
- Configuration parameters often represent a failure to decide — each parameter is complexity pushed onto the caller
- When in doubt, implement the simpler, more general-purpose approach first
Code applications:
| Context | Pattern | Example |
|---|---|---|
| API generality | Design for the concept, not one use case | text.insert(position, string) instead of text.addBulletPoint() |
| Reduce configuration | Determine behavior automatically | Auto-detect file encoding instead of an encoding parameter |
| Avoid over-specialization | One general method over many specific ones | store(key, value, options) instead of storeUser(), storeProduct(), storeOrder() |
See references/general-vs-special.md when choosing how general an interface should be — the "simplest interface for all current needs" test, the configuration-parameter antipattern, and push-complexity-downward worked through.
5. Comments as Design Documentation
Core concept: Comments should describe what is not obvious from the code: design intent, abstraction rationale, invariants, and assumptions. "Good code is self-documenting" is a myth for anything beyond low-level implementation detail.
Why it works: Code can only ever record what it does — never why this approach over the alternatives, or what it silently assumes. That rationale is the most perishable information in a system: it lives only in the author's head and is gone the moment they move on, so a comment is the single chance to capture it.
Key insights:
- Four types: interface comments (most important — they define the abstraction), data structure member comments, implementation comments, cross-module comments
- Write comments first (comment-driven design) to clarify thinking before code
- Don't repeat what the code makes clear; keep comments next to the code they describe and update them together
- If a comment is hard to write, the design may be too complex
Code applications:
| Context | Pattern | Example |
|---|---|---|
| Interface comment | Describe the abstraction, not the implementation | "Returns the widget closest to position, or null if none within threshold" |
| Data structure comment | Explain invariants | "List is sorted by priority descending; ties broken by insertion order" |
| Implementation comment | Explain why, not what | "// Binary search: list is always sorted, can hold 100k+ items" |
| Cross-module comment | Link related decisions | "// This timeout must match the retry interval in RetryPolicy.java" |
See references/comments-as-design.md when writing or reviewing comments and unsure what belongs in one — the four comment types with examples, the comment-driven-design procedure, and the rebuttal to the self-documenting-code myth.
6. Strategic vs Tactical Programming
Core concept: Tactical programming gets features working quickly and accumulates complexity with each shortcut. Strategic programming invests 10-20% extra effort in good design, treating every change as an opportunity to improve structure.
Why it works: Tactical speed is borrowed: each shortcut makes future changes harder, while the strategic investment compounds — strategically designed systems are faster to work with within months.
Key insights:
- Tactical tornado: a developer who ships fast but leaves wreckage — celebrated short-term, destructive long-term
- Your primary job is a great design that happens to work, not working code that happens to have a design
- Startups need strategic programming most — early shortcuts compound into crippling debt as the team grows
- Every change is an investment opportunity: leave the code a little better; refactoring is part of every feature, not a special event
Code applications:
| Context | Pattern | Example |
|---|---|---|
| Tactical trap | Resist quick-and-dirty fixes | Don't add a boolean parameter for "just this one special case" |
| Strategic investment | Improve structure during feature work | Refactor an awkward module interface while adding the feature |
| Design reviews | Evaluate structure, not just correctness | Ask "does this make the system simpler?" not just "does it work?" |
See references/strategic-programming.md when deciding how much design effort a change deserves, or making the case for it — the 10-20% investment math, the tactical-tornado pattern, and why startups need strategic programming most.
Common Mistakes
| Mistake | Why It Fails | Fix |
|---|---|---|
| Creating too many small classes | Classitis добавляет интерфейсы без глубины; каждая граница — это когнитивные издержки | Объединяйте связанные поверхностные классы в более глубокие модули |
| Разделение модулей по временному порядку | "Прочитать, затем обработать, затем записать" вынуждает разделять знание между модулями | Группируйте код, разделяющий знание, в один модуль |
| Раскрытие реализации в интерфейсах | Вызывающие зависят от внутренностей; изменения распространяются | Проектируйте интерфейсы вокруг абстракций; скрывайте форматы и протоколы |
| Отношение к комментариям как к необязательным | Замысел дизайна и допущения теряются; новички ошибаются в догадках | Сначала пишите комментарии к интерфейсу; поддерживайте их вместе с кодом |
| Параметры конфигурации для всего | Параметр, переложенный на вызывающего, — это решение, которое вы отказались принимать (см. §4) | Определяйте поведение автоматически; предоставляйте разумные значения по умолчанию |
| Быстрые и грязные тактические исправления | Компромиссы накапливаются, пока система не станет неработоспособной | Вкладывайте дополнительные 10-20%; рассматривайте каждое изменение как возможность для дизайна |
| Сквозные методы | Метод, который лишь передаёт свои аргументы другому, добавляет интерфейс, но не функциональность | Объедините сквозной метод с вызывающим или вызываемым |
| Проектирование под конкретные случаи использования | Интерфейсы специального назначения накапливают особые случаи | Спросите: простейший интерфейс, покрывающий все текущие потребности? |
Быстрая диагностика
| Вопрос | If No | Действие |
|---|---|---|
| Можете ли вы описать каждый модуль одним предложением? | Модули делают слишком много или лишены назначения | Разделите на связные, описываемые обязанности |
| Проще ли интерфейсы, чем реализации? | Модули поверхностны — сложность просачивается наружу | Скрывайте больше; объединяйте поверхностные классы в более глубокие |
| Можете ли вы изменить реализацию, не затрагивая вызывающих? | Информация просачивается через границы | Инкапсулируйте утёкшее знание в одном модуле |
| Описывают ли комментарии к интерфейсу абстракцию? | Замысел дизайна потерян; модуль будут использовать неправильно | Документируйте, что модуль обещает, а не как он работает |
| Является ли обсуждение дизайна частью код-ревью? | Ревью ловят баги, но не рост сложности | Добавьте "снижает ли это сложность?" в критерии ревью |
| Скрывает ли каждый модуль важное проектное решение? | Модули организованы вокруг кода, а не информации | Реорганизуйте так, чтобы каждый модуль владел конкретным знанием |
| Может ли новичок понять границы модулей, не читая реализации? | Абстракции недокументированы или протекают | Улучшайте комментарии к интерфейсу; упрощайте интерфейсы |
| Тратите ли вы 10-20% времени на улучшение дизайна? | Долг накапливается с каждой функцией | Включайте улучшение дизайна в каждый PR |
Дополнительное чтение
Для полной методологии с подробными примерами:
- "A Philosophy of Software Design" автор John Ousterhout (2-е издание)
Об авторе
John Ousterhout — профессор компьютерных наук Bosack Lerner в Стэнфорде и создатель скриптового языка Tcl и инструментария Tk. Он разработал A Philosophy of Software Design на основе своего курса Stanford CS 190, обобщив десятилетия опыта построения систем в принципы, применимые в разных языках и масштабах.
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: software-design-philosophy](https://darkplay.ru/ai/skills/wondelai-skills-software-design-philosophy)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
A11y Architectaffaan-m · Архитектор доступности, специализирующийся на соответствии WCAG 2.2 для веба и нативных…
Architectaffaan-m · Специалист по архитектуре ПО для проектирования систем, масштабируемости и принятия…
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
Gan Planneraffaan-m · GAN Harness — агент-планировщик: разворачивает промпт в полную спецификацию продукта.
Homelab Architectaffaan-m · Проектирует сети для дома и малой лаборатории с поэтапными изменениями и откатом.
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
Swift Revieweraffaan-m · Ревьюер Swift-кода: протокол-ориентированный дизайн, ARC, Swift Concurrency.
Type Design Analyzeraffaan-m · Анализ дизайна типов: инкапсуляция, инварианты, полезность, соблюдение.
example-skillsanthropics · Набор примеров навыков, демонстрирующих разные возможности: создание навыков, разработку…Лучшие ИИ-инструменты для программирования
Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные
GenAPIGenapi
Notepad++ AINotepad-plus-plus
Creatium MaxCremax
Emacs AIGnu
KiteKite
Amazon Q DeveloperAmazonЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachat