Skip to content
Back to skills

Code Principles

ASecurity

Use when in planning mode or making structural decisions to apply SOLID, DRY, Occam's Razor, Miller's Law, and YAGNI with a defined priority order. Helps resolve principle conflicts and guides architecture choices across any language.

  • 5 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added November 28, 2026
businesstypescriptpythonrustgosqlexpressapisecurity

Works with

  • api

Security analysis

A100/100

Scanned November 28, 2026

npx -y skills add trampo-framework/trampo --skill code-principles --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Code Principles?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Code Principles
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/trampo-framework-code-principles/badge)](https://www.skillsdirectory.com/skills/trampo-framework-code-principles)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: code-principles
description: Use when in planning mode or making structural decisions to apply SOLID, DRY, Occam's Razor, Miller's Law, and YAGNI with a defined priority order. Helps resolve principle conflicts and guides architecture choices across any language.
---

# Code Principles

Apply these principles during planning and structural decisions. When principles conflict, follow the priority order below.

**Apply sparingly.** Invoke a principle only when it changes the recommendation. Do not enumerate all six for every decision: naming every principle is noise. Cite the one or two that actually drive the call and stay silent on the rest.

## When to Skip
- One-off scripts, spikes, or throwaway prototypes (unless they handle user data or secrets: Safety First always applies)
- Pure test code (test readability trumps DRY; some duplication is acceptable for clarity)
- Trivial changes (renaming, formatting, dependency bumps)
- Non-structural asks: naming (domains, variables), copy, infra/transport selection, or "which tool/service already exists?" questions. Answer these directly; invoke a principle only if a structural choice is genuinely embedded. **Exception: if the choice affects security posture (suppressing security findings, authorization, data exposure, who-can-do-what), Safety First still applies; it is never a skippable "tooling" decision.** When only part of a request is structural, apply the principles to that part and handle the rest plainly.

## User Intent Overrides
These priorities govern the AI's default reasoning. If the user explicitly states a requirement or constraint that conflicts with the priority order, the user's stated intent takes precedence.

## Priority Order

When principles conflict, the higher-priority principle wins:

1. **Safety First**: Security, data integrity, correctness
2. **YAGNI**: Don't build what you don't need yet
3. **Occam's Razor**: Prefer the simplest solution that works
4. **SOLID**: Structure complex systems for maintainability
5. **DRY**: Eliminate duplicated knowledge (not at the cost of clarity)
6. **Miller's Law**: Respect the 7±2 cognitive limit in APIs, parameters, and module boundaries

## Quick Decision Questions

Before writing or approving code, ask:

- "Is there a simpler way?" → Occam's Razor
- "Understandable in under 1 minute?" → Miller's Law
- "Am I duplicating knowledge?" → DRY
- "Is this needed right now?" → YAGNI
- "Is this safe by default?" → Safety First

## Principles with Examples

### Safety First

Never compromise security or data integrity for elegance.

```typescript
// BAD: trusts caller input for authorization
function getUser(userId: string) {
  return db.users.find(userId);
}

// GOOD: validates access at the boundary
function getUser(userId: string, requesterId: string) {
  const user = db.users.find(userId);
  if (user.ownerId !== requesterId) throw new ForbiddenError();
  return user;
}
```

In practice, enforce authorization at the boundary (middleware, controller); this example illustrates the principle, not the ideal layer.

Safety checklist:
- Parameterize all queries (SQL, NoSQL, ORM)
- Validate and sanitize inputs at system boundaries
- Never log secrets, tokens, or PII
- Use allowlists over denylists for input filtering
- Default to deny/closed/private
- Audit dependencies for known vulnerabilities
- Treat data-integrity hazards as Safety, not style: stale/derived-index drift, selecting the wrong record on ambiguous input, double-spend / double-submit, and lost updates are Safety First, never traded off under Occam's Razor or SOLID. But escalate only *real* hazards: if inspecting the code or data disproves the risk, drop it: don't manufacture a safety gate to look thorough.

### YAGNI: You Aren't Gonna Need It

Build for today's requirements. Remove speculative code. If a requirement is confirmed and scheduled, it's not speculative: plan for it.

```typescript
// BAD: supports 3 export formats when only CSV is needed
interface ExportStrategy { export(data: Row[]): Buffer; }
class CsvExport implements ExportStrategy { /* ... */ }
class JsonExport implements ExportStrategy { /* ... */ }
class XmlExport implements ExportStrategy { /* ... */ }

// GOOD: just do what's needed
function exportCsv(data: Row[]): Buffer {
  return Buffer.from(data.map(r => r.join(",")).join("\n"));
}
```

When you need JSON export later, add it then, not now.

**Exception, known abstraction boundaries:** External service integrations (payment providers, email, storage, auth) are well-known volatility points. A thin interface at these boundaries is justified even with a single implementation.

### Occam's Razor: Simplest Solution

Given two solutions that solve the problem, pick the simpler one.

```typescript
// BAD: over-engineered event system for a single notification
class EventBus { /* publish/subscribe/middleware/retry... */ }
eventBus.publish("user.created", user);

// GOOD: direct call when there's one consumer
async function onUserCreated(user: User) {
  await sendWelcomeEmail(user.email);
}
```

Add the event bus when you actually have multiple consumers.

### SOLID: For Complex Systems

Apply when the system has real complexity that justifies the structure. This section focuses on Single Responsibility and Dependency Inversion, the most frequently relevant. Open/Closed, Liskov Substitution, and Interface Segregation apply but arise less often.

**Single Responsibility**: One reason to change per module.

```typescript
// BAD: handler does validation, business logic, and persistence
async function handleOrder(req: Request) {
  if (!req.body.items?.length) throw new Error("empty");
  const total = req.body.items.reduce((s, i) => s + i.price, 0);
  await db.orders.insert({ items: req.body.items, total });
  await emailService.send(req.body.email, total);
}

// GOOD: each concern is separated
async function handleOrder(req: Request) {
  const input = validateOrderInput(req.body);
  const order = createOrder(input);
  await saveOrder(order);
  await notifyCustomer(order);
}
```

**Dependency Inversion**: Depend on abstractions at system boundaries.

```typescript
// GOOD: swappable storage behind an interface
interface OrderStore {
  save(order: Order): Promise<void>;
}

function createOrderService(store: OrderStore) {
  return {
    async place(input: OrderInput) {
      const order = createOrder(input);
      await store.save(order);
      return order;
    },
  };
}
```

But don't create interfaces for internal code with a single implementation: that's YAGNI.

### DRY: Don't Repeat Knowledge

Eliminate duplication of **knowledge**, not just characters. Three similar lines are fine if they represent different concepts.

```typescript
// BAD: duplicated validation rule
function validateOnCreate(email: string) {
  if (!email.includes("@")) throw new Error("invalid");
}
function validateOnUpdate(email: string) {
  if (!email.includes("@")) throw new Error("invalid");
}

// GOOD: single source of truth for the rule
function validateEmail(email: string) {
  if (!email.includes("@")) throw new Error("invalid email");
}
```

```typescript
// DON'T over-DRY: these look similar but represent different concepts
const userQuery = `SELECT id, name FROM users WHERE active = true`;
const adminQuery = `SELECT id, name FROM admins WHERE active = true`;
// Merging these into buildActiveQuery(table) adds coupling for no real gain
```

### Miller's Law: 7±2 Cognitive Limit

Functions, configs, and APIs should not exceed what a person can hold in working memory.

```typescript
// BAD: 11 parameters, no one remembers the order
function createUser(name, email, age, role, dept, manager,
  startDate, salary, currency, location, timezone) { /* ... */ }

// GOOD: grouped into a coherent object
interface CreateUserInput {
  name: string;
  email: string;
  role: Role;
  department: Department;
  startDate: Date;
}
function createUser(input: CreateUserInput) { /* ... */ }
```

Also applies to: module public APIs, config options, conditional branches in a function, items in an enum exposed to users.

Rule of thumb: flag when a function exceeds 5 parameters, a module exposes more than 7 public functions, or a conditional has more than 5 branches.

## Language-Specific Notes

These principles are language-agnostic, but their expression varies:
- **Rust**: The compiler enforces memory safety; focus Safety First on logic errors and `unsafe` blocks.
- **Go**: Prefer concrete types until a second implementation exists (YAGNI). Interfaces are implicit and cheap; use them at consumption site.
- **Python**: Use `typing.Protocol` over ABC inheritance for Dependency Inversion. Avoid metaprogramming as a DRY mechanism when it hurts readability.

Adapt the TypeScript examples above to the target language's idioms.

## Conflict Resolution Examples

| Situation | Winning Principle | Reasoning |
|---|---|---|
| "Add an abstraction layer for future DB swap" | YAGNI over SOLID | No current need for the swap |
| "Inline the SQL to keep it simple" but it handles user input | Safety over Occam's | Must parameterize queries regardless of simplicity |
| "Extract a helper" but it's used once | YAGNI over DRY | One callsite doesn't justify extraction |
| "Split into 12 micro-modules" | Miller's Law over SOLID | Too many modules defeats comprehension |
| "Copy-paste is simpler" but it's a business rule | DRY over Occam's | Duplicated business rules diverge and cause bugs |

## Applying During Planning

When reviewing or creating a plan, validate each component against:

1. Does any part introduce a security risk? → Fix it regardless of other tradeoffs
2. Is any part speculative or not required by current scope? → Remove it
3. Is there a simpler design that satisfies the requirements? → Use it
4. For remaining complexity, is the structure maintainable? → Apply SOLID
5. Is any knowledge duplicated? → Consolidate if it won't hurt clarity
6. Can someone new understand each piece quickly? → Simplify interfaces

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in business →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.