/house-style:coding-effectivelyfrom house-style
Guides code design, writing, editing, refactoring, debugging, and review with dependency management best practices and sub-skills for security and testing.
Ships in house-style. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
ALWAYS REQUIRED:
defense-in-depth - Validate at every layer data passes throughCONDITIONAL: Use these sub-skills when applicable:
howto-develop-with-postgres - PostgreSQL database codewriting-good-tests - Writing or reviewing testsproperty-based-testing - Tests for serialization, validation, normalization, pure functionsCurrying, dependency injection, and interfaces are one move: turn a hidden coupling into an explicit parameter, give it the narrowest useful type, and bind it as late as the budget allows. This guide is about doing that successfully, which means knowing when not to.
The first principle is economic, not moral: every seam costs indirection — a cognitive hop for the reader and often a dispatch for the machine. So the default is concrete, and you buy a seam only when it pays rent. "Program to an interface" is advice, not a commandment; applied dogmatically it produces codebases that are abstract everywhere and flexible nowhere.
A unit whose dependencies are all parameters is a pure function: output determined by input, nothing else. That single property gives you everything downstream — it's testable (pass a different value), reasoned-about (substitute equals for equals), and swappable (the boundary varies independently of the core). The goal is always the same shape: determinism in the middle, substitutability at the edge.
You do not get that shape by abstracting everything. You get it by abstracting the right things and leaving the rest concrete.
Add one only when the dependency has a real axis of variation. In practice that's a short list:
| Add a seam | Because |
|---|---|
| Nondeterminism — clock, randomness, UUIDs | The real value is uncontrollable; a parameter makes the unit deterministic and testable. |
| I/O & external systems — DB, network, filesystem, queues | This is your failure/latency boundary — the seam lets you inject retries, breakers, timeouts, and fault injectors. |
| Genuine deployment variation — payment provider, storage backend, config, feature flags | More than one implementation actually ships or is imminent. |
That's roughly it. Note the unifying trait: each is nondeterministic, effectful, external, or genuinely plural. If a dependency is none of those, it does not need a seam.
new the value.Clock is worth it and UserNameFormatter isn't.)System (touches everything) is explicit but useless — the type no longer bounds the blast radius. Inject the capability, not the container.() => number, not Clock, when all you need is the time. Clock, not System, when you need a small set of related operations. The type should be a manifest of exactly what the unit can touch — and therefore a guarantee of what it can't.main), where a human can read the whole thing at a glance. No magic, no scanning, no annotations resolved at runtime.Nondeterminism — and notice the seam is a plain parameter, not an interface.
// Hidden dependency on the wall clock: nondeterministic, untestable.
function isExpired(token: Token): boolean {
return token.expiresAt < Date.now();
}
// The clock is now an input. Deterministic, trivially testable, zero ceremony.
function isExpired(token: Token, now: number): boolean {
return token.expiresAt < now;
}
You needed a number, so you passed a number. Reach for an interface only when the dependency has behavior worth faking (several methods, state, real swap). Not everything that gets injected deserves a type with a name.
Over-abstraction — the seam that buys nothing.
// Speculative: one implementation, no axis of variation, wired through a container.
interface UserNameFormatter {
format(u: User): string;
}
class DefaultUserNameFormatter implements UserNameFormatter {
format(u: User) {
return `${u.first} ${u.last}`;
}
}
// It was always just a function.
const formatUserName = (u: User) => `${u.first} ${u.last}`;
Inject the capability, not the world.
// `system` can reach the clock, the filesystem, the network, env... blast radius = everything.
class Report {
constructor(private system: System) {}
build() {
const t = this.system.clock.now(); /* ... */
}
}
// The type now tells you the entire surface this class can touch.
class Report {
constructor(private now: () => number) {}
build() {
const t = this.now(); /* ... */
}
}
() => number over Clock; Clock over System.)North star. Default to concrete. Add a seam when a dependency is nondeterministic, effectful, external, or genuinely varies — give it the narrowest type that does the job, wire it in plain code, and keep the core pure. Abstractions are bought with indirection; make each one pay rent. Everything called "good design" — testable, readable, swappable, provable — falls out of that one discipline, applied with judgment rather than reflex.
The one idea. A type is a predicate over values, an invariant a predicate over states, a class the machinery that establishes and preserves an invariant by owning every door into its state. All three separate valid from invalid and keep you in the valid region inductively: establish the property at a boundary, preserve it under every permitted operation, and then assume it everywhere else for free. That "assume it for free" is the prize — it's where readable, testable, low-bug code comes from, because it lets every other line reason locally.
This guide is about applying that idea with judgment. The principles are a gradient of effort, not a set of commandments. The goal is correctness you can afford, not maximal encoding. Most of the wins come from the cheapest rungs; the expensive ones are for code that has earned them.
insert on a sorted structure returns a sorted structure, callers compose without re-checking. Closure is what lets you avoid re-validation.Make illegal states unrepresentable — when the distinction drives behavior.
Replace flag soup with a sum type. bool loading; bool error; T? data (which permits nonsense like loading-and-errored) becomes Loading | Failed(e) | Loaded(data). Use distinct newtypes for things that shouldn't mix (UserId vs OrderId, not both string). Use NonEmptyList, NonZero, Positive so the empty/zero/negative case is gone from the body rather than guarded in it.
Parse, don't validate — at every point where untrusted shape becomes trusted shape.
A validator returns bool and throws the knowledge away; a parser returns the refined type and keeps it. parseEmail(s) -> Option<Email>; then everything downstream takes Email, never re-checking a raw string. The type is the proof the check happened.
Smart constructors — when the type system can't express the invariant. Sorted, balanced, in-range-across-fields, summing-to-100 — make the raw constructor private, expose one factory that establishes and asserts the invariant. One door, checked once.
Encapsulate for the invariant, not reflexively. Hide exactly what protects the invariant; expose the rest plainly. A class with a getter and setter for every field protects nothing — it's a struct wearing a disguise, and a plain record is more honest and more readable.
Assertions for the un-typeable.
For invariants the language won't carry, assert/debug_assert at construction and after mutation. Executable documentation that fails near the cause. Cheap, removable in release, invaluable in debug.
Closure and total functions.
Prefer operations that return the same refined type. Make partiality explicit with Result/Option rather than throwing — but only when you actually handle it; a swallowed error is a lie wearing an honest type's clothes.
At trust and process boundaries. Validate untrusted input once at the edge, convert to trusted types, trust within. For invariants that span processes, you have no shared memory and no atomic method call — design for idempotency, monotonicity, and commutativity (CRDTs are the clean version: convergence preserved by construction). Don't pretend a class invariant crosses the network.
Spend the least that's adequate. Climb only when stakes and violation-likelihood justify it.
| Rung | Mechanism | Use when |
|---|---|---|
| 1 | Unrepresentable (types) | The invariant is cheap to encode and the language carries it naturally. Best ROI when it fits. |
| 2 | Enforced at one constructor / parser | Can't be static, but there's a natural single entry point. |
| 3 | Asserted + property-tested | No clean static or constructor enforcement; you want it caught in CI and debug builds. |
| 4 | Documented + tested at the chokepoint | Spans systems you don't own (distributed, third-party, eventual consistency). Name the limit of the guarantee honestly. |
Climbing past the rung an invariant deserves is itself a defect: it costs compile time, comprehension, and hiring, and it buries the load-bearing constraints under ceremony.
These are the ways the discipline turns against itself. Watch for them.
// INVARIANT: plus an assert plus a focused test is sometimes more readable and just as safe. Clever types carry the same liability as clever anything.Result, hides failure rather than handling it. Honest means the signature tells the truth about how it fails, not that it never does.In one line: find the invariant, establish it at one door, keep every operation from breaking it, let the rest of the program assume it for free — and spend no more than the invariant is worth.
How to use functional discipline to write good code — and how to know when to stop applying it.
The point of all of this is not purity. It is honesty about state and effects, kept local. You reach for each practice below because it removes more complexity than it adds. When it stops doing that, you stop. Every rule here ships with the condition under which you break it.
Make the hidden dependencies in your code — mutation, failure, absence, I/O, time — explicit and local. A function should be honest about what it touches, and what it touches should be as small as possible. Everything else is tactics.
The dogma trap is treating "pure" as the goal. The goal is reasoning — yours, the next person's, and the compiler's. Spend discipline where reasoning pays off (concurrency, security boundaries, money, the long-lived core domain) and relax it where it doesn't (scripts, glue, prototypes, hot inner loops behind a clean interface).
Do it: Expected, recoverable failure returns Result<T, E>. Possible absence returns Option<T>. The caller is forced to confront both at compile time instead of discovering them in production.
fn charge(account: &Account, cents: u64) -> Result<Receipt, ChargeError>;
// ^ the contract names what can go wrong
Relax it when:
Result. Don't make callers handle "this can't happen."Result<T, Infallible> to look consistent.Option would propagate ten layers unchanged — supply a default at the boundary and pass the plain value inward.Smell: a signature that lies — returns T but throws, or claims to be infallible while reading a mutable global.
The test is one question: will the caller do something different because of this?
Result/Option.Relax it when: you're at a top-level boundary — a request handler, a CLI main, a job runner. Collapsing many possible failures into one error boundary there is fine; you don't need to thread Result through code whose only response is "log it and return 500." Push the ceremony to where decisions actually branch.
Do it: Computation and decisions live in a pure core that takes data and returns data. I/O lives in a thin shell that feeds the core and performs whatever the core decided.
// core: pure, returns a description of what to do — trivially testable
fn plan(order: &Order, inventory: &Inventory) -> Vec<Command> { /* ... */ }
// shell: performs the effects, holds the danger, stays thin
for cmd in plan(&order, &inventory) {
execute(cmd)?; // the only place that touches the world
}
This is the highest-leverage pattern here: the core needs no mocks, and the effects are concentrated where you can watch them.
Relax it when: the program is mostly effects (an ETL job, a device driver, a streaming pipeline). The shell can be thick when the domain is genuinely effectful. Don't contort an inherently stateful thing — a parser, a connection pool, an allocator — into a pure shape it doesn't want. A stateful object with a clean interface is sometimes the honest model.
The sin is shared, observable mutable state, not mutation itself. A local mutation that no caller can observe is still referentially transparent.
fn checksum(bytes: &[u8]) -> u32 {
let mut acc = 0u32; // local mutation, invisible outside
for &b in bytes { acc = acc.wrapping_mul(31).wrapping_add(b as u32); }
acc // caller sees a pure function
}
Do it: Default to immutable values and transformations. Share nothing across threads/modules by default.
Relax it when: you're in a hot path. Mutate a local buffer or accumulator, reuse allocations, avoid building a fresh collection per element — all fine, provided the mutation stays inside the function and the interface stays honest. Persistent data structures are a tool, not a tax you must always pay.
Do it: Encode invariants in types so wrong states won't compile. Parse untrusted input once, at the boundary, into a precise type that carries the proof inward.
struct Email(String);
impl Email {
fn parse(s: &str) -> Result<Email, EmailError> { /* validate once */ }
}
// everything downstream takes Email, never re-checks a raw &str
Prefer sum types over flag soup (enum State beats three correlated bools), and NonEmpty<T> over "a Vec that must not be empty, see comment."
Relax it when: the type costs more than the bug it prevents. A 30-line script doesn't need a type lattice. Some invariants are cheaper as a runtime check in one smart constructor than as a type-level proof. Stop when the types get harder to read than the rule they encode.
Smell: the same validation repeated at many call sites; boolean-blind parameters; comments saying "this string is really a path / JSON / an ID."
Do it: A public contract tells the truth about what it does — can it fail, does it do I/O — and nothing about how. The interface can be pure even when the implementation mutates a local arena.
Relax it when: the caller needs to control the mechanism. If latency, ordering, or batching matters to the caller, hiding it is the wrong encapsulation — you've concealed what matters and exposed what doesn't. And don't build an abstraction boundary around something with one caller; that's ceremony, not design.
?, flatMap, and do-notation let you chain context-carrying computations and refactor the pipeline fearlessly; the monad laws are why the refactor is safe.
Relax it when: the abstraction is harder to read than the code it abstracts. Deep monad-transformer stacks and six-layer effect towers are a smell. Flatten them: a concrete application type, a small effect enum, or language-level effects/async beats a generic tower nobody on the team can read. Generality that isn't used is just cost.
Do it: Unit-test the pure core with plain values and property tests over invariants. Integration-test the thin shell where it meets the world.
Relax it / read the signal: if testing the core requires mocking the universe, the effects have leaked into the core. The fix is the design, not more mocks — pull the I/O back out to the shell. A handful of real integration tests at the seam beat a hundred brittle mock-heavy ones.
Every practice here has a cost: async colors every caller, immutability allocates, effect towers obscure, and all of it loads the team's working memory. None of that means don't do it — it means spend it deliberately.
The mature version of this discipline doesn't look maximally functional. It looks honest: minimal effects, kept at the edges, around a core you can actually reason about — and pragmatic mutation everywhere that honesty isn't at stake.
When designing features, think about properties upfront. This surfaces design gaps early.
Discovery questions:
| Question | Property Type | Example |
|---|---|---|
| Does it have an inverse operation? | Roundtrip | decode(encode(x)) == x |
| Is applying it twice the same as once? | Idempotence | f(f(x)) == f(x) |
| What quantities are preserved? | Invariants | Length, sum, count unchanged |
| Is order of arguments irrelevant? | Commutativity | f(a, b) == f(b, a) |
| Can operations be regrouped? | Associativity | f(f(a,b), c) == f(a, f(b,c)) |
| Is there a neutral element? | Identity | f(x, 0) == x |
| Is there a reference implementation? | Oracle | new(x) == old(x) |
| Can output be easily verified? | Easy to verify | is_sorted(sort(x)) |
Common design questions these reveal:
Surface these during design, not during debugging.
Model the full error space. No shortcuts.
Don't:
any or equivalent to bypass type checkingTwo-tier model:
Error message format: Lowercase sentence fragments for "failed to {message}".
Good: failed to connect to database: connection refused
Bad: Failed to Connect to Database: Connection Refused
Good: invalid configuration: missing required field 'apiKey'
Bad: Invalid Configuration: Missing Required Field 'apiKey'
Lowercase fragments compose naturally: "operation failed: " + error.message reads correctly.
Always use proper logging, and errors should always be logged via the language/framework appropriate methods.
The rule of three applies to abstraction: Don't abstract until you've seen the pattern three times. Three similar lines of code is better than a premature abstraction.
Name files by what they contain, not by generic categories.
Don't create:
utils.go - Becomes a dumping ground for unrelated functionshelpers.js - Same problemcommon.rs - What isn't common?misc.go - Actively unhelpfulDo create:
formatter.go - String manipulation utilitiescalendar/math.go - Date calculationsapi/src/error_handling.rs - API error utilitiesuser-input.ts - User input validationWhy this matters:
string-formatting.tsimport { formatDate } from './date-arithmetic' is self-documentingWhen you're tempted to create utils.ts: Stop. Ask what the functions have in common. Name the file after that commonality.
unix.go, windows.go, posix.goDon't emulate Unix on Windows or vice versa. Use each platform's native patterns.
Bad: Trying to make Windows paths behave like Unix paths everywhere.
Good: Accept platform differences, handle them explicitly.
// Platform-specific behavior
if (process.platform === "win32") {
// Windows-native approach
} else {
// POSIX approach
}
When platform differences are significant, use separate files:
process/spawn.go // Shared interface and logic
process/unix.go // Unix-specific implementation
process/windows.go // Windows-specific implementation
When behavior differs by platform, document it in comments:
// On Windows, this returns CRLF line endings.
// On Unix, this returns LF line endings.
// Callers should normalize if consistent output is needed.
function readTextFile(path: string): string { ... }
Don't assume Unix behavior works on Windows. Test explicitly:
| Mistake | Reality | Fix |
|---|---|---|
| "Just put it in utils for now" | utils.ts becomes 2000 lines of unrelated code | Name files by purpose from the start |
| "Edge cases are rare" | Edge cases cause production incidents | Handle them. Model the full error space. |
| "We might need this abstraction later" | Premature abstraction is harder to remove than add | Wait for the third use case |
| "It works on my Mac" | It may not work on Windows or Linux | If deploying to a target, test on it |
| "The type system is too strict" | Strictness catches bugs at compile time | Fix the type error, don't bypass it |
Stop and refactor when you see:
utils.go or helpers.rs file growing beyond 100 linesany) to bypass the type systemWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub pbdeuchler/llm-plugins --plugin house-style9 skills in this plugin
/authoring-issuesUse when asked to write, draft, file, or open a GitHub issue - mandates exploring the relevant code to understand the whole problem space, reasoning any proposed solution, and structuring the issue with summary, what/why, references, nuances, open questions, and acceptance criteria. Adds professionalism and no-sensitive-info discipline for public repos./defense-in-depthUse when invalid data causes failures deep in execution - validates at every layer data passes through to make bugs structurally impossible rather than temporarily fixed/holistic-reviewUse when reviewing a completed implementation holistically - a finished branch, a completed plan step, or a diff before PR. Reviews every changed line against the implementation plan (if one exists) and high engineering standards across seven dimensions, verifies tests by deliberately breaking crucial code, and emits severity-classified findings with a PASS/FAIL verdict./howto-develop-with-postgresUse when writing database access code, creating schemas, or managing transactions with PostgreSQL - enforces transaction safety with TX_ naming, read-write separation, type safety for UUIDs/JSONB, and snake_case conventions to prevent data corruption and type errors/issue-hygieneUse when creating, editing, triaging, or cleaning up GitHub issues - a mechanical pass that verifies the title is accurate and current, labels/assignees/milestone are correct, and the body is valid, well-formed markdown, all via the gh CLI. Does not judge content quality./property-based-testingUse when writing tests for serialization, validation, normalization, or pure functions - provides property catalog, pattern detection, and library reference for property-based testingOther plugins' skills for the same job