docq 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. docq-0.1.0/.claude/skills/software-design-philosophy/SKILL.md +280 -0
  2. docq-0.1.0/.claude/skills/software-design-philosophy/references/comments-as-design.md +387 -0
  3. docq-0.1.0/.claude/skills/software-design-philosophy/references/complexity-symptoms.md +209 -0
  4. docq-0.1.0/.claude/skills/software-design-philosophy/references/deep-modules.md +347 -0
  5. docq-0.1.0/.claude/skills/software-design-philosophy/references/general-vs-special.md +342 -0
  6. docq-0.1.0/.claude/skills/software-design-philosophy/references/information-hiding.md +336 -0
  7. docq-0.1.0/.claude/skills/software-design-philosophy/references/strategic-programming.md +269 -0
  8. docq-0.1.0/.docq/config.json +12 -0
  9. docq-0.1.0/.gitignore +29 -0
  10. docq-0.1.0/.python-version +1 -0
  11. docq-0.1.0/CLAUDE.md +64 -0
  12. docq-0.1.0/LICENSE +21 -0
  13. docq-0.1.0/PKG-INFO +112 -0
  14. docq-0.1.0/README.md +96 -0
  15. docq-0.1.0/corpora/aposd/.gitkeep +2 -0
  16. docq-0.1.0/corpora/aposd/cases.yaml +994 -0
  17. docq-0.1.0/corpora/aposd/profile.py +17 -0
  18. docq-0.1.0/corpora/aposd/prompt-questions.md +39 -0
  19. docq-0.1.0/corpora/aposd/prompt.md +29 -0
  20. docq-0.1.0/corpora/aposd/screen_candidates.py +137 -0
  21. docq-0.1.0/corpora/aposd/taxonomy.yaml +227 -0
  22. docq-0.1.0/docs/ARCHITECTURE.md +350 -0
  23. docq-0.1.0/docs/BUILDS.md +353 -0
  24. docq-0.1.0/docs/CLI.md +423 -0
  25. docq-0.1.0/docs/DESIGN.md +544 -0
  26. docq-0.1.0/docs/STARTUP_GUIDE.md +169 -0
  27. docq-0.1.0/docs/TESTING.md +190 -0
  28. docq-0.1.0/docs/superpowers/notes/2026-06-10-corpus-generation-prompts.md +61 -0
  29. docq-0.1.0/docs/superpowers/notes/2026-06-10-full-book-build-handoff.md +82 -0
  30. docq-0.1.0/docs/superpowers/notes/2026-06-10-naming.md +19 -0
  31. docq-0.1.0/docs/superpowers/notes/2026-06-10-session-handoff.md +84 -0
  32. docq-0.1.0/docs/superpowers/notes/2026-06-10-taxonomy-reconciliation.md +145 -0
  33. docq-0.1.0/docs/superpowers/plans/2026-06-10-aposd-embedded.md +1090 -0
  34. docq-0.1.0/docs/superpowers/plans/2026-06-10-aposd-full-book-build.md +787 -0
  35. docq-0.1.0/docs/superpowers/plans/2026-07-10-retrieval-tracks-overview.md +98 -0
  36. docq-0.1.0/docs/superpowers/plans/2026-07-10-track-a-compact-skill.md +78 -0
  37. docq-0.1.0/docs/superpowers/plans/2026-07-10-track-b-rerank.md +62 -0
  38. docq-0.1.0/docs/superpowers/plans/2026-07-10-track-c-question-topup.md +79 -0
  39. docq-0.1.0/docs/superpowers/plans/2026-07-10-track-d-eval-expansion.md +68 -0
  40. docq-0.1.0/docs/superpowers/specs/2026-06-10-aposd-embedded-design.md +392 -0
  41. docq-0.1.0/pyproject.toml +32 -0
  42. docq-0.1.0/src/docq/__init__.py +11 -0
  43. docq-0.1.0/src/docq/build.py +127 -0
  44. docq-0.1.0/src/docq/cli.py +404 -0
  45. docq-0.1.0/src/docq/config.py +203 -0
  46. docq-0.1.0/src/docq/enrich.py +149 -0
  47. docq-0.1.0/src/docq/evalrun.py +84 -0
  48. docq-0.1.0/src/docq/extract.py +86 -0
  49. docq-0.1.0/src/docq/parse.py +127 -0
  50. docq-0.1.0/src/docq/profile.py +43 -0
  51. docq-0.1.0/src/docq/rerank.py +193 -0
  52. docq-0.1.0/src/docq/segment.py +168 -0
  53. docq-0.1.0/src/docq/store.py +114 -0
  54. docq-0.1.0/src/docq/taxonomy.py +41 -0
  55. docq-0.1.0/src/docq/topup.py +146 -0
  56. docq-0.1.0/src/docq/vectors.py +312 -0
  57. docq-0.1.0/tests/__init__.py +0 -0
  58. docq-0.1.0/tests/conftest.py +24 -0
  59. docq-0.1.0/tests/test_build.py +117 -0
  60. docq-0.1.0/tests/test_cli.py +104 -0
  61. docq-0.1.0/tests/test_config.py +73 -0
  62. docq-0.1.0/tests/test_enrich.py +174 -0
  63. docq-0.1.0/tests/test_eval.py +80 -0
  64. docq-0.1.0/tests/test_extract.py +56 -0
  65. docq-0.1.0/tests/test_parse.py +48 -0
  66. docq-0.1.0/tests/test_rerank.py +138 -0
  67. docq-0.1.0/tests/test_segment.py +185 -0
  68. docq-0.1.0/tests/test_stdlib_contract.py +21 -0
  69. docq-0.1.0/tests/test_store.py +44 -0
  70. docq-0.1.0/tests/test_taxonomy.py +47 -0
  71. docq-0.1.0/tests/test_topup.py +152 -0
  72. docq-0.1.0/tests/test_vectors.py +172 -0
  73. docq-0.1.0/uv.lock +1008 -0
@@ -0,0 +1,280 @@
1
+ ---
2
+ name: software-design-philosophy
3
+ description: 'Manage software complexity through deep modules, information hiding, and strategic programming. This skill is a practical breakdown of the principles from John Ousterhout's "A Philosophy Of Software Design". Use when designing a new complex feature or when refactoring existing complex code to apply these principles.'
4
+ license: MIT
5
+ metadata:
6
+ author: wondelai
7
+ version: "1.2.0"
8
+ ---
9
+
10
+ # A Philosophy of Software Design Framework
11
+
12
+ 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. The central thesis is that complexity is the root cause of most software problems, and managing it requires deliberate, strategic thinking at every level of design.
13
+
14
+ ## Core Principle
15
+
16
+ **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. Every design decision should be evaluated by asking: "Does this increase or decrease the overall complexity of the system?" The goal is not zero complexity -- that is impossible in useful software -- but to minimize unnecessary complexity and concentrate necessary complexity where it can be managed.
17
+
18
+ ## Consulting the Source (gloss corpus)
19
+
20
+ This repo may carry a queryable corpus of the book itself: `gloss` returns Ousterhout's
21
+ **actual passages** with citations, not a paraphrase. When the corpus is available,
22
+ ground design answers in it — a verbatim passage with a page number beats this file's
23
+ distillation.
24
+
25
+ **Availability check:** the corpus db is `build/minimax-v2.db`; if that file is absent,
26
+ use the live db named in `CLAUDE.md`. If no db exists, skip this section and work from
27
+ the bundled [reference files](#reference-files) as usual.
28
+
29
+ **How to query:**
30
+
31
+ ```bash
32
+ uv run gloss retrieve "<symptom-phrased query>" --db build/minimax-v2.db -k 3 --compact
33
+ ```
34
+
35
+ - Phrase the query as a developer's *symptom* ("callers have to call setup in the right
36
+ order", "my class just forwards calls and adds nothing"), not book vocabulary
37
+ ("temporal decomposition").
38
+ - **Rewrite before you query.** Expand a terse, noisy, or multi-concern situation into
39
+ ONE complete symptom sentence covering ONE concern ("big function split?" → "is a long
40
+ function that does several sequential things automatically a problem"); fire separate
41
+ queries for separate concerns. Measured effect: ~+7 points hit@1 on realistic queries.
42
+ If the situation is already a well-formed single-concern symptom sentence, use it
43
+ as-is — over-elaborating an already-sharp query makes results worse.
44
+ - When you already know which principle applies, narrow with `--principle <slug>`. The
45
+ slugs are the six principles below: `complexity`, `deep-modules`,
46
+ `information-hiding`, `general-purpose`, `comments`, `strategic-programming`.
47
+
48
+ **Reading the output:** the top hit prints in full — citation header + verbatim
49
+ passage. Runners-up print as one `more: id=N [citation] (type via tags) — <paraphrase>`
50
+ preview line each.
51
+
52
+ **Trust rules:**
53
+
54
+ - Top hit tagged `via lex#N+sem#M` (both channels present) = two independent retrieval
55
+ signals agree — high confidence; quote it.
56
+ - Channels disagree (one-channel tag like `via sem#4`), or a `more:` preview matches
57
+ the situation better than the top hit? Expand that unit before answering:
58
+ `uv run gloss show <id> --db build/minimax-v2.db`.
59
+ - **Never answer from a preview line.** Its text is a generated paraphrase, not the
60
+ passage — the verbatim promise applies only to passage bodies. Expand with
61
+ `gloss show` and quote the source's own words.
62
+ - No hits, or nothing fits the situation? Rephrase once with different symptom
63
+ vocabulary. Still nothing → fall back to the bundled reference files.
64
+
65
+ **Cite what you quote:** pass the citation through — `[deep-modules §4.6 p.45]` tells
66
+ the reader exactly where in the book the passage lives.
67
+
68
+ ## Scoring
69
+
70
+ **Goal: 10/10.** When reviewing or creating software designs, rate them 0-10 based on adherence to the principles below. A 10/10 means deep modules with clean abstractions, excellent information hiding, strategic thinking about complexity, and comments that capture design intent. Lower scores indicate shallow modules, information leakage, tactical shortcuts, or missing design documentation. Always provide the current score and specific improvements needed to reach 10/10.
71
+
72
+ ## The Software Design Framework
73
+
74
+ Six principles for managing complexity and producing systems that are easy to understand and modify:
75
+
76
+ ### 1. Complexity and Its Causes
77
+
78
+ **Core concept:** Complexity is anything related to the structure of a software system that makes it hard to understand and modify. It manifests through three symptoms: change amplification, cognitive load, and unknown unknowns.
79
+
80
+ **Why it works:** By identifying the specific symptoms of complexity, developers can diagnose problems precisely rather than relying on vague notions of "messy code." The two fundamental causes -- dependencies and obscurity -- provide clear targets for design improvement.
81
+
82
+ **Key insights:**
83
+ - Change amplification: a simple change requires modifications in many places
84
+ - Cognitive load: a developer must hold too much information in mind to make a change
85
+ - Unknown unknowns: it is not obvious what needs to be changed, or what information is relevant (the worst symptom)
86
+ - Dependencies: code cannot be understood or modified in isolation
87
+ - Obscurity: important information is not obvious from the code or documentation
88
+ - Complexity is incremental -- it accumulates from hundreds of small decisions, not one big mistake
89
+ - The "death by a thousand cuts" nature of complexity means every decision matters
90
+
91
+ **Code applications:**
92
+
93
+ | Context | Pattern | Example |
94
+ |---------|---------|---------|
95
+ | **Change amplification** | Centralize shared knowledge | Extract color constants instead of hardcoding `#ff0000` in 20 files |
96
+ | **Cognitive load** | Reduce what developers must know | Use a simple `open(path)` API instead of requiring buffer size, encoding, and lock mode |
97
+ | **Unknown unknowns** | Make dependencies explicit | Use type systems and interfaces to surface what a change affects |
98
+ | **Dependency management** | Minimize cross-module coupling | Pass data through well-defined interfaces, not shared global state |
99
+ | **Obscurity reduction** | Name things precisely | `numBytesReceived` not `n`; `retryDelayMs` not `delay` |
100
+
101
+ See: [references/complexity-symptoms.md](references/complexity-symptoms.md)
102
+
103
+ ### 2. Deep vs Shallow Modules
104
+
105
+ **Core concept:** The best modules are deep: they provide powerful functionality behind a simple interface. Shallow modules have complex interfaces relative to the functionality they provide, adding complexity rather than reducing it.
106
+
107
+ **Why it works:** A module's interface represents the complexity it imposes on the rest of the system. Its implementation represents the functionality it provides. Deep modules give you a high ratio of functionality to interface complexity. The interface is the cost; the implementation is the benefit.
108
+
109
+ **Key insights:**
110
+ - A module's depth = functionality provided / interface complexity imposed
111
+ - Deep modules: simple interface, powerful implementation (Unix file I/O, garbage collectors)
112
+ - Shallow modules: complex interface, limited implementation (Java I/O wrapper classes)
113
+ - "Classitis": the disease of creating too many small, shallow classes
114
+ - Each interface adds cognitive load -- more classes does not mean better design
115
+ - The best abstractions hide significant complexity behind a few simple concepts
116
+ - Small methods are not inherently good; depth matters more than size
117
+
118
+ **Code applications:**
119
+
120
+ | Context | Pattern | Example |
121
+ |---------|---------|---------|
122
+ | **Deep module** | Hide complexity behind simple API | `file.read(path)` hides disk blocks, caching, buffering, encoding |
123
+ | **Shallow module** | Avoid thin wrappers that just pass through | A `FileInputStream` wrapped in `BufferedInputStream` wrapped in `ObjectInputStream` |
124
+ | **Classitis cure** | Merge related shallow classes | Combine `RequestParser`, `RequestValidator`, `RequestProcessor` into one `RequestHandler` |
125
+ | **Method depth** | Methods should do something substantial | A `delete(key)` that handles locking, logging, cache invalidation, and rebalancing |
126
+ | **Interface simplicity** | Fewer parameters, fewer methods | `config.get(key)` with sensible defaults, not 15 constructor parameters |
127
+
128
+ See: [references/deep-modules.md](references/deep-modules.md)
129
+
130
+ ### 3. Information Hiding and Leakage
131
+
132
+ **Core concept:** Each module should encapsulate knowledge that is not needed by other modules. Information leakage -- when a design decision is reflected in multiple modules -- is one of the most important red flags in software design.
133
+
134
+ **Why it works:** When information is hidden inside a module, changes to that knowledge require modifying only that module. When information leaks across module boundaries, changes propagate through the system. Information hiding reduces both dependencies and obscurity, the two fundamental causes of complexity.
135
+
136
+ **Key insights:**
137
+ - Information hiding: embed knowledge of a design decision in a single module
138
+ - Information leakage: the same knowledge appears in multiple modules (a red flag)
139
+ - Temporal decomposition causes leakage: splitting code by when things happen forces shared knowledge across phases
140
+ - Back-door leakage through data formats, protocols, or shared assumptions is the subtlest form
141
+ - Decorators are frequent sources of leakage -- they expose the decorated interface
142
+ - If two modules share knowledge, consider merging them or creating a new module that encapsulates the shared knowledge
143
+
144
+ **Code applications:**
145
+
146
+ | Context | Pattern | Example |
147
+ |---------|---------|---------|
148
+ | **Information hiding** | Encapsulate format details | One module owns the HTTP parsing logic; callers get structured objects |
149
+ | **Temporal decomposition** | Organize by knowledge, not time | Combine "read config" and "apply config" into a single config module |
150
+ | **Format leakage** | Centralize serialization | One module handles JSON encoding/decoding rather than spreading `json.dumps` everywhere |
151
+ | **Protocol leakage** | Abstract protocol details | A `MessageBus.send(event)` hides whether transport is HTTP, gRPC, or queue |
152
+ | **Decorator leakage** | Use deep wrappers sparingly | Prefer adding buffering inside the file class over wrapping it externally |
153
+
154
+ See: [references/information-hiding.md](references/information-hiding.md)
155
+
156
+ ### 4. General-Purpose vs Special-Purpose Modules
157
+
158
+ **Core concept:** Design modules that are "somewhat general-purpose": the interface should be general enough to support multiple uses without being tied to today's specific requirements, while the implementation handles current needs. Ask: "What is the simplest interface that will cover all my current needs?"
159
+
160
+ **Why it works:** General-purpose interfaces tend to be simpler because they eliminate special cases. They also future-proof the design since new use cases often fit the existing abstraction. However, over-generalization wastes effort and can itself introduce complexity through unnecessary abstractions.
161
+
162
+ **Key insights:**
163
+ - "Somewhat general-purpose" is the sweet spot between too specific and too generic
164
+ - The key question: "What is the simplest interface that will cover all my current needs?"
165
+ - General-purpose interfaces are often simpler than special-purpose ones (fewer special cases)
166
+ - Push complexity downward: modules at lower levels should handle hard cases so upper levels stay simple
167
+ - Configuration parameters often represent failure to determine the right behavior -- each parameter is complexity pushed to the caller
168
+ - When in doubt, implement the simpler, more general-purpose approach first
169
+
170
+ **Code applications:**
171
+
172
+ | Context | Pattern | Example |
173
+ |---------|---------|---------|
174
+ | **API generality** | Design for the concept, not one use case | A `text.insert(position, string)` API instead of `text.addBulletPoint()` |
175
+ | **Push complexity down** | Handle defaults in the module | A web server that picks reasonable buffer sizes instead of requiring callers to configure them |
176
+ | **Reduce configuration** | Determine behavior automatically | Auto-detect file encoding instead of requiring an `encoding` parameter |
177
+ | **Avoid over-specialization** | Remove use-case-specific methods | One `store(key, value, options)` instead of `storeUser()`, `storeProduct()`, `storeOrder()` |
178
+ | **Somewhat general** | General interface, specific implementation | A `Datastore` interface that currently backs onto PostgreSQL but does not expose SQL concepts |
179
+
180
+ See: [references/general-vs-special.md](references/general-vs-special.md)
181
+
182
+ ### 5. Comments as Design Documentation
183
+
184
+ **Core concept:** Comments should describe things that are not obvious from the code. They capture design intent, abstraction rationale, and information that cannot be expressed in code. The claim that "good code is self-documenting" is a myth for anything beyond low-level implementation details.
185
+
186
+ **Why it works:** Code tells you what the program does, but not why it does it that way, what the design alternatives were, or what assumptions the code makes. Comments capture the designer's mental model -- the abstraction -- which is the most valuable and most perishable information in a system.
187
+
188
+ **Key insights:**
189
+ - Four types: interface comments, data structure member comments, implementation comments, cross-module comments
190
+ - Interface comments are the most important: they define the abstraction a module presents
191
+ - Write comments first (comment-driven design) to clarify your thinking before writing code
192
+ - "Self-documenting code" works only for low-level what; it fails for why, assumptions, and abstractions
193
+ - Comments should describe what is not obvious -- if the code makes it clear, don't repeat it
194
+ - Maintain comments near the code they describe; update them when the code changes
195
+ - If a comment is hard to write, the design may be too complex
196
+
197
+ **Code applications:**
198
+
199
+ | Context | Pattern | Example |
200
+ |---------|---------|---------|
201
+ | **Interface comment** | Describe the abstraction, not the implementation | "Returns the widget closest to the given position, or null if no widgets exist within the threshold distance" |
202
+ | **Data structure comment** | Explain invariants and constraints | "List is sorted by priority descending; ties are broken by insertion order" |
203
+ | **Implementation comment** | Explain why, not what | "// Use binary search here because the list is always sorted and can contain 100k+ items" |
204
+ | **Cross-module comment** | Link related design decisions | "// This timeout must match the retry interval in RetryPolicy.java" |
205
+ | **Comment-driven design** | Write the interface comment before the code | Draft the function's contract and behavior first, then implement |
206
+
207
+ See: [references/comments-as-design.md](references/comments-as-design.md)
208
+
209
+ ### 6. Strategic vs Tactical Programming
210
+
211
+ **Core concept:** Tactical programming focuses on getting features working quickly, accumulating complexity with each shortcut. Strategic programming invests 10-20% extra effort in good design, treating every change as an opportunity to improve the system's structure.
212
+
213
+ **Why it works:** Tactical programming appears faster in the short term but steadily degrades the codebase, making every future change harder. Strategic programming produces a codebase that stays easy to modify over time. The small upfront investment compounds -- systems designed strategically are faster to work with after a few months.
214
+
215
+ **Key insights:**
216
+ - Tactical tornado: a developer who produces features fast but leaves wreckage behind; often celebrated short-term but destructive long-term
217
+ - Strategic mindset: your primary job is to produce a great design that also happens to work, not working code that happens to have a design
218
+ - The 10-20% investment: spend roughly 10-20% of development time on design improvement
219
+ - Startups need strategic programming most -- early design shortcuts compound into crippling technical debt as the team grows
220
+ - "Move fast and break things" culture (early Facebook) vs design-focused culture (Google) -- Google engineers were more productive on complex systems
221
+ - Every code change is an investment opportunity: leave the code a little better than you found it
222
+ - Refactoring is not a special event -- it is part of every feature's development
223
+
224
+ **Code applications:**
225
+
226
+ | Context | Pattern | Example |
227
+ |---------|---------|---------|
228
+ | **Tactical trap** | Resist quick-and-dirty fixes | Don't add a boolean parameter to handle "just this one special case" |
229
+ | **Strategic investment** | Improve structure during feature work | When adding a feature, refactor the module interface if it has become awkward |
230
+ | **Tactical tornado** | Recognize and intervene | A developer who writes 2x the code but creates 3x the maintenance burden |
231
+ | **Startup discipline** | Invest in design from day one | Clean module boundaries and good abstractions even under time pressure |
232
+ | **Incremental improvement** | Fix one design issue per PR | Each pull request improves at least one abstraction or eliminates one piece of complexity |
233
+ | **Design reviews** | Evaluate structure, not just correctness | Code reviews should ask "does this make the system simpler?" not just "does it work?" |
234
+
235
+ See: [references/strategic-programming.md](references/strategic-programming.md)
236
+
237
+ ## Common Mistakes
238
+
239
+ | Mistake | Why It Fails | Fix |
240
+ |---------|-------------|-----|
241
+ | **Creating too many small classes** | Classitis adds interfaces without adding depth; each class boundary is cognitive overhead | Merge related shallow classes into deeper modules with simpler interfaces |
242
+ | **Splitting modules by temporal order** | "Read, then process, then write" forces shared knowledge across three modules | Organize around information: group code that shares knowledge into one module |
243
+ | **Exposing implementation in interfaces** | Callers depend on internal details; changes propagate everywhere | Design interfaces around abstractions, not implementations; hide format and protocol details |
244
+ | **Treating comments as optional** | Design intent, assumptions, and abstractions are lost; new developers guess wrong | Write interface comments first; maintain them as the code evolves |
245
+ | **Configuration parameters for everything** | Each parameter pushes a decision to the caller, increasing cognitive load | Determine behavior automatically; provide sensible defaults; minimize required configuration |
246
+ | **Quick-and-dirty tactical fixes** | Each shortcut adds a small amount of complexity; over time the system becomes unworkable | Invest 10-20% extra in good design; treat every change as a design opportunity |
247
+ | **Pass-through methods** | Methods that just delegate to another method add interface without adding depth | Merge the pass-through into the caller or the callee |
248
+ | **Designing for specific use cases** | Special-purpose interfaces accumulate special cases and become bloated | Ask "what is the simplest interface that covers all current needs?" |
249
+
250
+ ## Quick Diagnostic
251
+
252
+ | Question | If No | Action |
253
+ |----------|-------|--------|
254
+ | Can you describe what each module does in one sentence? | Modules are doing too much or have unclear purpose | Split into modules with coherent, describable responsibilities |
255
+ | Are interfaces simpler than implementations? | Modules are shallow -- they leak complexity outward | Redesign to hide more; merge shallow classes into deeper ones |
256
+ | Can you change a module's implementation without affecting callers? | Information is leaking across module boundaries | Identify leaked knowledge and encapsulate it inside one module |
257
+ | Do interface comments describe the abstraction, not the code? | Design intent is lost; developers will misuse the module | Write comments that explain what the module promises, not how it works |
258
+ | Is design discussion part of code reviews? | Reviews only catch bugs, not complexity growth | Add "does this reduce or increase system complexity?" to review criteria |
259
+ | Does each module hide at least one important design decision? | Modules are organized around code, not around information | Reorganize so each module owns a specific piece of knowledge |
260
+ | Can a new team member understand module boundaries without reading implementations? | Abstractions are not documented or are too leaky | Improve interface comments and simplify interfaces until they are self-evident |
261
+ | Are you spending 10-20% of time on design improvement? | Technical debt is accumulating with every feature | Adopt a strategic mindset; include design improvement in every PR |
262
+
263
+ ## Reference Files
264
+
265
+ - [complexity-symptoms.md](references/complexity-symptoms.md): Three symptoms of complexity, two causes, measuring complexity, the incremental nature of complexity
266
+ - [deep-modules.md](references/deep-modules.md): Deep vs shallow modules, interface-to-functionality ratio, classitis, designing for depth
267
+ - [information-hiding.md](references/information-hiding.md): Information hiding principle, information leakage red flags, temporal decomposition, decorator pitfalls
268
+ - [general-vs-special.md](references/general-vs-special.md): Somewhat general-purpose approach, pushing complexity down, configuration parameter antipattern
269
+ - [comments-as-design.md](references/comments-as-design.md): Four comment types, comment-driven design, self-documenting code myth, maintaining comments
270
+ - [strategic-programming.md](references/strategic-programming.md): Strategic vs tactical mindset, tactical tornado, investment approach, startup considerations
271
+
272
+ ## Further Reading
273
+
274
+ This skill is based on John Ousterhout's practical guide to software design. For the complete methodology with detailed examples:
275
+
276
+ - [*"A Philosophy of Software Design"*](https://www.amazon.com/Philosophy-Software-Design-2nd/dp/173210221X?tag=wondelai00-20) by John Ousterhout (2nd edition)
277
+
278
+ ## About the Author
279
+
280
+ **John Ousterhout** is the Bosack Lerner Professor of Computer Science at Stanford University. He is the creator of the Tcl scripting language and the Tk toolkit, and co-founded several companies including Electric Cloud and Clustrix. Ousterhout has received numerous awards, including the ACM Software System Award, the UC Berkeley Distinguished Teaching Award, and the USENIX Lifetime Achievement Award. He developed *A Philosophy of Software Design* from his CS 190 course at Stanford, where students work on multi-phase software design projects and learn to recognize and reduce complexity. The book distills decades of experience in building systems software and teaching software design into a concise set of principles that apply across languages, paradigms, and system scales. Now in its second edition, the book has become a widely recommended resource for software engineers seeking to improve their design skills beyond correctness and into clarity.
@@ -0,0 +1,387 @@
1
+ # Comments as Design Documentation
2
+
3
+ Comments are one of the most debated topics in software engineering. Ousterhout argues that comments are not merely helpful -- they are essential design documentation that captures information that cannot be expressed in code. The belief that "good code is self-documenting" is partially true for implementation details, but dangerously wrong for abstractions, design decisions, and cross-cutting concerns.
4
+
5
+
6
+ ## Table of Contents
7
+ 1. [Why Comments Matter](#why-comments-matter)
8
+ 2. [The Four Types of Comments](#the-four-types-of-comments)
9
+ 3. [Comment-Driven Design](#comment-driven-design)
10
+ 4. [The "Self-Documenting Code" Myth](#the-self-documenting-code-myth)
11
+ 5. [Maintaining Comments](#maintaining-comments)
12
+ 6. [Comments Anti-Patterns](#comments-anti-patterns)
13
+ 7. [Summary](#summary)
14
+
15
+ ---
16
+
17
+ ## Why Comments Matter
18
+
19
+ Code tells you **what** the program does. Comments tell you:
20
+ - **Why** it does it that way
21
+ - **What** the abstraction promises (the contract)
22
+ - **What** assumptions the code makes
23
+ - **What** alternatives were considered and rejected
24
+ - **What** constraints link this code to other modules
25
+ - **What** is not obvious from reading the code
26
+
27
+ Without comments, this information exists only in the original developer's head. When that developer moves on, the information is lost. Future developers must reverse-engineer intent from implementation -- an error-prone process that leads to incorrect changes and accumulated complexity.
28
+
29
+ ## The Four Types of Comments
30
+
31
+ ### 1. Interface Comments
32
+
33
+ **Purpose:** Define the abstraction that a module, class, or function presents to its users.
34
+
35
+ **This is the most important type of comment.** Interface comments form the contract between a module and its callers. They should describe:
36
+ - What the function/method does (at an abstract level)
37
+ - What each parameter means and its constraints
38
+ - What the return value represents
39
+ - What side effects occur
40
+ - What exceptions can be thrown and under what conditions
41
+ - What the caller must ensure before calling (preconditions)
42
+ - What the caller can assume after the call (postconditions)
43
+
44
+ **Examples:**
45
+
46
+ ```python
47
+ def find_nearest(target: Point, candidates: list[Point],
48
+ max_distance: float = inf) -> Point | None:
49
+ """Find the candidate point closest to target.
50
+
51
+ Returns the nearest point from candidates, or None if no candidate
52
+ is within max_distance of target. If multiple candidates are
53
+ equidistant, returns the one that appears first in the list.
54
+
55
+ Args:
56
+ target: The reference point to measure distances from.
57
+ candidates: Points to search. Must not be empty.
58
+ max_distance: Maximum Euclidean distance to consider.
59
+ Points farther than this are ignored. Defaults to
60
+ infinity (consider all points).
61
+
62
+ Returns:
63
+ The nearest Point, or None if all candidates exceed
64
+ max_distance.
65
+
66
+ Raises:
67
+ ValueError: If candidates is empty.
68
+ """
69
+ ```
70
+
71
+ ```java
72
+ /**
73
+ * Acquire a database connection from the pool.
74
+ *
75
+ * Blocks until a connection is available or the timeout expires.
76
+ * The returned connection is guaranteed to be valid (tested with
77
+ * a lightweight query before returning). The caller MUST close
78
+ * the connection when done, which returns it to the pool.
79
+ *
80
+ * @param timeout maximum time to wait for a connection
81
+ * @return a valid, open database connection
82
+ * @throws TimeoutException if no connection is available within timeout
83
+ * @throws PoolExhaustedException if the pool is permanently full
84
+ * (all connections in use and at max capacity)
85
+ */
86
+ public Connection acquire(Duration timeout)
87
+ ```
88
+
89
+ **Key rules for interface comments:**
90
+ - Describe the abstraction, not the implementation
91
+ - If the comment mentions implementation details (algorithms, data structures, internal variables), it is too detailed
92
+ - A developer should be able to use the module correctly by reading only the interface comment, without reading any implementation code
93
+ - If you cannot write a clear interface comment, the interface may be poorly designed
94
+
95
+ ### 2. Data Structure Member Comments
96
+
97
+ **Purpose:** Explain the meaning, constraints, and invariants of fields in a class or data structure.
98
+
99
+ Field names alone rarely convey all the information a developer needs. Comments should clarify:
100
+ - What the field represents (especially if the name is ambiguous)
101
+ - Units and encoding (milliseconds? seconds? UTC? local time?)
102
+ - Valid ranges and boundary conditions
103
+ - Relationships with other fields
104
+ - When the field is set and when it may be null/zero
105
+
106
+ **Examples:**
107
+
108
+ ```python
109
+ class RetryConfig:
110
+ # Maximum number of retry attempts before giving up.
111
+ # Does not count the initial attempt, so total attempts = max_retries + 1.
112
+ # Set to 0 to disable retries.
113
+ max_retries: int
114
+
115
+ # Base delay between retries in milliseconds.
116
+ # Actual delay uses exponential backoff: base_delay_ms * 2^attempt.
117
+ # Jitter of +/- 20% is applied to prevent thundering herd.
118
+ base_delay_ms: int
119
+
120
+ # Maximum delay cap in milliseconds. Exponential backoff will
121
+ # not exceed this value regardless of attempt number.
122
+ # Must be >= base_delay_ms.
123
+ max_delay_ms: int
124
+ ```
125
+
126
+ ```java
127
+ class PageCache {
128
+ // Maps page_id to cached page content. Entries are evicted
129
+ // in LRU order when the cache exceeds maxEntries. A page
130
+ // present in this map is guaranteed to match the on-disk
131
+ // version as of the last sync (see lastSyncTime).
132
+ private Map<Long, Page> cache;
133
+
134
+ // Timestamp of the last cache synchronization with disk,
135
+ // in epoch milliseconds (UTC). All cache entries are valid
136
+ // as of this time. Writes after this time may not be reflected.
137
+ private long lastSyncTime;
138
+
139
+ // Upper bound on cache entries. When exceeded, the least
140
+ // recently accessed entry is evicted before inserting a new one.
141
+ // Invariant: cache.size() <= maxEntries at all times.
142
+ private int maxEntries;
143
+ }
144
+ ```
145
+
146
+ ### 3. Implementation Comments
147
+
148
+ **Purpose:** Explain **why** the code does something a particular way, or clarify non-obvious logic.
149
+
150
+ Implementation comments should not describe **what** the code does -- that should be clear from reading the code itself. They should explain:
151
+ - Why this approach was chosen over alternatives
152
+ - What non-obvious constraint or edge case the code handles
153
+ - What would go wrong if the code were changed in an obvious-seeming way
154
+ - Performance considerations that drove the implementation choice
155
+
156
+ **Good implementation comments:**
157
+
158
+ ```python
159
+ # Use binary search instead of linear scan because the list is sorted
160
+ # and can contain 100k+ entries. Linear scan caused 200ms latency
161
+ # in production (see incident #4521).
162
+ index = bisect.bisect_left(sorted_entries, target)
163
+ ```
164
+
165
+ ```python
166
+ # Process items in reverse order to avoid index invalidation when
167
+ # removing elements. Forward iteration would skip elements after
168
+ # each removal.
169
+ for i in range(len(items) - 1, -1, -1):
170
+ if should_remove(items[i]):
171
+ items.pop(i)
172
+ ```
173
+
174
+ ```python
175
+ # Intentionally catching broad Exception here because the third-party
176
+ # library can throw undocumented exceptions (observed RuntimeError,
177
+ # ValueError, and OSError in production). We log and continue rather
178
+ # than crash the batch job.
179
+ try:
180
+ result = third_party_lib.process(data)
181
+ except Exception as e:
182
+ logger.warning(f"Processing failed for {data.id}: {e}")
183
+ result = default_result()
184
+ ```
185
+
186
+ **Bad implementation comments (just repeat the code):**
187
+
188
+ ```python
189
+ # Increment counter
190
+ counter += 1
191
+
192
+ # Check if user is active
193
+ if user.is_active:
194
+
195
+ # Loop through items
196
+ for item in items:
197
+
198
+ # Return the result
199
+ return result
200
+ ```
201
+
202
+ These comments add no information. The code already says what it does. Remove them.
203
+
204
+ ### 4. Cross-Module Comments
205
+
206
+ **Purpose:** Document dependencies and design decisions that span multiple modules.
207
+
208
+ These are the hardest comments to maintain but often the most critical, because cross-module relationships are the biggest source of unknown unknowns.
209
+
210
+ **Examples:**
211
+
212
+ ```python
213
+ # This timeout value must be longer than the retry timeout in
214
+ # RetryPolicy (currently 30s with 3 retries = 90s max). If this
215
+ # timeout is shorter, the caller will give up before retries complete.
216
+ # See: src/retry/policy.py:RetryPolicy.MAX_TOTAL_DURATION
217
+ REQUEST_TIMEOUT_SECONDS = 120
218
+ ```
219
+
220
+ ```python
221
+ # The field order in this struct must match the binary protocol
222
+ # defined in docs/protocol-v3.md section 4.2. The client parser
223
+ # (client/src/parser.rs) reads fields in this exact order.
224
+ # Changing field order here requires updating both the docs and
225
+ # the client parser.
226
+ class ServerMessage:
227
+ version: int # 2 bytes, big-endian
228
+ message_type: int # 1 byte
229
+ payload_len: int # 4 bytes, big-endian
230
+ payload: bytes # payload_len bytes
231
+ ```
232
+
233
+ ```java
234
+ /**
235
+ * IMPORTANT: This method is called by the EventBus on a background
236
+ * thread. It must not access the UI thread directly. Use
237
+ * Platform.runLater() for any UI updates.
238
+ *
239
+ * The EventBus guarantees at-least-once delivery, so this handler
240
+ * must be idempotent. See EventBus.subscribe() docs for details.
241
+ */
242
+ public void onOrderCompleted(OrderCompletedEvent event) {
243
+ ```
244
+
245
+ **Best practices for cross-module comments:**
246
+ - Place the comment in the most likely place a developer would look
247
+ - Reference the other module explicitly (file path, class name)
248
+ - Explain what would go wrong if the relationship were violated
249
+ - Consider using a shared constants file for values that must stay in sync
250
+
251
+ ## Comment-Driven Design
252
+
253
+ **Write the comments before writing the code.**
254
+
255
+ This is one of Ousterhout's most practical recommendations. The process:
256
+
257
+ 1. **Write the interface comment first:** Before writing any implementation, write the comment that describes what the function/class/module does, what its parameters mean, and what it returns.
258
+
259
+ 2. **Evaluate the design:** If the interface comment is hard to write, unclear, or requires mentioning implementation details, the interface design is probably wrong. Redesign the interface until the comment is clean and simple.
260
+
261
+ 3. **Write the implementation:** With a clear interface comment as your guide, the implementation has a clear target.
262
+
263
+ 4. **Add implementation comments:** As you write code, add comments for any non-obvious decisions.
264
+
265
+ ### Why Comment-Driven Design Works
266
+
267
+ | Benefit | Explanation |
268
+ |---------|-------------|
269
+ | Forces clear thinking | Writing what something does before how reveals confusion early |
270
+ | Catches bad abstractions | If you can't describe the interface simply, it's too complex |
271
+ | Produces better interfaces | The act of writing clarifies what callers actually need |
272
+ | Comments stay accurate | Written alongside the design, not retrofitted later |
273
+ | Saves time | Avoids implementing a design that turns out to be wrong |
274
+
275
+ ### Example
276
+
277
+ **Step 1:** Write the interface comment.
278
+
279
+ ```python
280
+ def merge_sorted_streams(*streams: Iterator[T],
281
+ key: Callable = None) -> Iterator[T]:
282
+ """Merge multiple sorted iterators into a single sorted iterator.
283
+
284
+ Each input stream must be sorted in ascending order (or by key
285
+ if provided). The output yields all elements from all streams
286
+ in globally sorted order. Memory usage is O(num_streams),
287
+ regardless of stream length.
288
+
289
+ Equal elements are yielded in the order their source streams
290
+ appear in the arguments (stable merge).
291
+ """
292
+ ```
293
+
294
+ **Step 2:** Evaluate. Is this clear? Can a caller use this without reading the implementation? What about edge cases -- empty streams, single stream, duplicate elements? Add those details if needed.
295
+
296
+ **Step 3:** Implement. The comment now serves as the specification.
297
+
298
+ ## The "Self-Documenting Code" Myth
299
+
300
+ The claim that "good code doesn't need comments" contains a kernel of truth but is dangerously incomplete.
301
+
302
+ ### Where Self-Documenting Code Works
303
+
304
+ Code **can** document itself for low-level implementation details:
305
+
306
+ ```python
307
+ # This is self-documenting -- no comment needed:
308
+ total_price = sum(item.price for item in cart.items)
309
+ is_eligible = user.age >= 18 and user.has_valid_id
310
+ filtered = [x for x in data if x.is_active and x.score > threshold]
311
+ ```
312
+
313
+ Good variable names, clear control flow, and simple expressions make the **what** obvious. Comments that restate this are noise.
314
+
315
+ ### Where Self-Documenting Code Fails
316
+
317
+ Code **cannot** document:
318
+
319
+ | Information | Why Code Can't Express It | Example |
320
+ |------------|--------------------------|---------|
321
+ | **Abstractions** | Code shows implementation, not the promise | An interface's contract and guarantees |
322
+ | **Why** | Code shows what happens, not why this approach | Why binary search instead of hash lookup |
323
+ | **Constraints** | Code enforces constraints but doesn't explain them | Why a timeout is set to 120 seconds |
324
+ | **Design alternatives** | Code shows the choice made, not choices rejected | Why we chose polling over webhooks |
325
+ | **Cross-module relationships** | Code in one module can't describe its relationship to another | This timeout must match the retry config |
326
+ | **Performance rationale** | Optimized code is often less readable | Why we denormalized this data structure |
327
+ | **Assumptions** | Code operates on assumptions it cannot state | "This list is always sorted by the caller" |
328
+
329
+ ### The Practical Rule
330
+
331
+ **Use self-documenting code for the "what" (implementation). Use comments for the "why" (design decisions), the "what" at a higher level (abstractions/interfaces), and the "beware" (non-obvious constraints and relationships).**
332
+
333
+ ## Maintaining Comments
334
+
335
+ Comments that are wrong are worse than no comments. Here are strategies for keeping them accurate:
336
+
337
+ ### 1. Place Comments Near the Code
338
+
339
+ The closer a comment is to the code it describes, the more likely it will be updated when the code changes. Interface comments in the function signature are better than comments in a separate documentation file.
340
+
341
+ ### 2. Avoid Duplicating Information
342
+
343
+ If the same information is stated in a comment and enforced in code, one will eventually become stale. State each fact once.
344
+
345
+ ```python
346
+ # Bad: duplicates the type annotation
347
+ # max_retries is an integer representing the maximum number of retries
348
+ max_retries: int # The type already says it's an int
349
+
350
+ # Good: adds information not in the code
351
+ # Set to 0 to disable retries. Values > 10 are capped at 10 to prevent
352
+ # excessive load on the downstream service during outages.
353
+ max_retries: int
354
+ ```
355
+
356
+ ### 3. Update Comments in the Same Commit
357
+
358
+ Make it a code review norm: if you change a function's behavior, you must update its interface comment in the same commit. Stale comments are a code review finding.
359
+
360
+ ### 4. Use Comments as a Design Smell Detector
361
+
362
+ If a comment is hard to write, the code may be too complex. If a comment needs to be very long, the interface may be doing too much. If a comment keeps going out of date, the module's boundaries may be wrong. Difficult comments are a signal, not just a chore.
363
+
364
+ ### 5. Treat Comment Quality as a Review Criterion
365
+
366
+ In code reviews, evaluate comments alongside code:
367
+ - Are interface comments complete and accurate?
368
+ - Do implementation comments explain why, not what?
369
+ - Are cross-module comments present where needed?
370
+ - Are there missing comments on non-obvious code?
371
+
372
+ ## Comments Anti-Patterns
373
+
374
+ | Anti-Pattern | Problem | Fix |
375
+ |-------------|---------|-----|
376
+ | **Comment repeats the code** | Adds noise, no information | Delete it; let the code speak for implementation details |
377
+ | **Comment describes what, not why** | Misses the valuable information | Rewrite to explain the reasoning or design decision |
378
+ | **Comment on every line** | Obscures code, hard to maintain | Comment only non-obvious sections; trust clear code |
379
+ | **TODO without context** | "TODO: fix this" is useless months later | Include the issue number, the problem, and the fix direction |
380
+ | **Commented-out code** | Dead code that confuses readers | Delete it; version control preserves history |
381
+ | **Banner comments** | `/////// SECTION ///////` adds structure without information | Use meaningful function/class boundaries instead |
382
+ | **Apology comments** | "Sorry, this is a hack" acknowledges but doesn't fix | Fix the hack or add context on why it is necessary and when it can be fixed |
383
+ | **Stale comments** | Describe behavior that no longer exists | Update or remove in the same commit as the code change |
384
+
385
+ ## Summary
386
+
387
+ Comments are not a sign of bad code. They are design documentation that captures the most valuable and perishable information in a system: the designer's intent, the abstraction's contract, and the non-obvious relationships between components. Write interface comments first, maintain them alongside code, and use them as a tool for thinking clearly about design.