惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
小众软件
小众软件
博客园_首页
博客园 - 聂微东
V
V2EX
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
SegmentFault 最新的问题
J
Java Code Geeks
Last Week in AI
Last Week in AI
The Cloudflare Blog
月光博客
月光博客
雷峰网
雷峰网
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
人人都是产品经理
人人都是产品经理
博客园 - Franky
腾讯CDC
Jina AI
Jina AI
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
量子位
爱范儿
爱范儿
美团技术团队
T
Tailwind CSS Blog
博客园 - 【当耐特】
D
Docker
IT之家
IT之家
V
Visual Studio Blog
P
Proofpoint News Feed
L
LangChain Blog
Engineering at Meta
Engineering at Meta
C
Check Point Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog RSS Feed
Recorded Future
Recorded Future

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Spec Driven Development: Build Software That Actually Does What You Promised
JEFFERSON RO · 2026-04-30 · via DEV Community

Spec Driven Development: Build Software That Actually Does What You Promised

"A well-written specification is not a constraint on creativity — it's a contract that frees everyone to move fast with confidence."


The Problem We've All Lived

You've been there. A sprint ends, the feature ships, and someone from the QA team — or worse, the client — asks: "Wait, but what happens when the user submits a negative amount? What if the email is missing?"

Silence. Awkward GitHub blame. A hotfix at 11pm.

The root cause is almost never bad code. It's a missing or ambiguous specification. The developer built something — just not the right something, because no one clearly defined what "right" looked like before a single line was written.

This is the problem Spec Driven Development (SDD) solves.


What Is Spec Driven Development?

Spec Driven Development is a software methodology where a formal, machine-readable (or at minimum, unambiguous human-readable) specification is written and agreed upon before any implementation begins.

The spec becomes the single source of truth for:

  • What inputs are valid
  • What outputs are expected
  • What edge cases must be handled
  • What errors should be raised and when

Unlike TDD (Test Driven Development), which starts from test cases, SDD starts one layer above — from a contract between all stakeholders. Tests are then derived from the spec, not invented alongside the code.


SDD vs. Other Methodologies

TDD BDD SDD
Starts with Test cases User behavior scenarios Formal specification
Written by Developers Devs + QA + PO All stakeholders
Primary artifact Test file .feature file Spec document / schema
Code follows The tests The scenarios The spec
Catches Regressions Behavior gaps Contract violations

SDD doesn't replace TDD or BDD — it precedes them. Once your spec exists, you can generate tests from it automatically.


Core Principles of SDD

1. 🔏 The Spec Is Law

No behavior is implemented without being in the spec. No spec item goes unimplemented. The spec and the code stay in sync — if the spec changes, the code changes, and vice versa.

2. 📐 Precision Over Prose

Specs written in vague English ("the system should handle errors gracefully") are useless. Good specs define exactly what "gracefully" means: which HTTP status code, which error payload shape, which log level.

3. 🤝 Shared Ownership

The spec is co-authored. Developers, product managers, QA engineers, and sometimes clients all sign off. This eliminates the "that's not what I meant" conversation after delivery.

4. 🔄 Living Document

Specs evolve. But every change goes through a deliberate revision process — not a Slack message at 4pm asking to "quickly tweak something."


Real-World Example: A Payment Processing Module

Let's walk through SDD end-to-end using a concrete scenario.

📋 The Business Request

"We need a charge endpoint. It should take a user's card and amount, and process a payment."

Classic. Now watch how SDD transforms this vague request into airtight software.


Step 1: Write the Spec

Before touching an IDE, the team drafts the specification. We'll use OpenAPI 3.0 format — widely adopted, tooling-rich, and human-readable.

# payment-spec.yaml
openapi: 3.0.3
info:
  title: Payment Processing API
  version: 1.0.0

paths:
  /payments/charge:
    post:
      summary: Charge a payment method
      operationId: chargePayment
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChargeRequest'
      responses:
        '200':
          description: Payment successful
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChargeResponse'
        '400':
          description: Invalid request data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '402':
          description: Payment declined by provider
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Internal server error

components:
  schemas:
    ChargeRequest:
      type: object
      required: [amount, currency, card_token, idempotency_key]
      properties:
        amount:
          type: integer
          minimum: 50          # Minimum charge: $0.50 (in cents)
          maximum: 99999999    # Maximum charge: $999,999.99
          description: Amount in the smallest currency unit (e.g., cents for USD)
        currency:
          type: string
          enum: [USD, EUR, PEN, GBP]
          description: ISO 4217 currency code
        card_token:
          type: string
          pattern: '^tok_[a-zA-Z0-9]{24}$'
          description: Tokenized card reference from the frontend SDK
        idempotency_key:
          type: string
          minLength: 16
          maxLength: 64
          description: Client-generated unique key to prevent duplicate charges
        description:
          type: string
          maxLength: 255
          description: Optional human-readable description for the charge

    ChargeResponse:
      type: object
      required: [charge_id, status, amount, currency, created_at]
      properties:
        charge_id:
          type: string
          description: Unique identifier for this charge
        status:
          type: string
          enum: [succeeded, pending]
        amount:
          type: integer
        currency:
          type: string
        created_at:
          type: string
          format: date-time

    ErrorResponse:
      type: object
      required: [error_code, message]
      properties:
        error_code:
          type: string
          enum:
            - INVALID_AMOUNT
            - INVALID_CURRENCY
            - INVALID_CARD_TOKEN
            - CARD_DECLINED
            - INSUFFICIENT_FUNDS
            - DUPLICATE_IDEMPOTENCY_KEY
            - INTERNAL_ERROR
        message:
          type: string
        details:
          type: object

Enter fullscreen mode Exit fullscreen mode

Notice what just happened. In ~90 lines of YAML, we have answered:

  • ✅ What fields are required vs. optional?
  • ✅ What are the valid currencies?
  • ✅ What's the minimum and maximum charge?
  • ✅ What does the card token format look like?
  • ✅ What exact error codes exist, and when?
  • ✅ What does a success response look like?

Zero ambiguity. Every stakeholder reviews and signs off on this before Sprint 1 starts.


Step 2: Generate Validation From the Spec

With a spec in place, we don't write validation logic by hand — we generate it. Tools like ajv, zod, or fastify's built-in schema support can consume OpenAPI schemas directly.

// src/schemas/chargeSchema.ts
import { z } from 'zod';

// This mirrors our OpenAPI spec exactly — one source of truth
export const ChargeRequestSchema = z.object({
  amount: z
    .number()
    .int()
    .min(50, 'Amount must be at least 50 cents')
    .max(99_999_999, 'Amount exceeds maximum allowed'),
  currency: z.enum(['USD', 'EUR', 'PEN', 'GBP']),
  card_token: z
    .string()
    .regex(/^tok_[a-zA-Z0-9]{24}$/, 'Invalid card token format'),
  idempotency_key: z.string().min(16).max(64),
  description: z.string().max(255).optional(),
});

export type ChargeRequest = z.infer<typeof ChargeRequestSchema>;

Enter fullscreen mode Exit fullscreen mode


Step 3: Implement Against the Contract

Now developers write the controller. The spec is their guide — they're not making design decisions on the fly.

// src/controllers/paymentController.ts
import { Request, Response } from 'express';
import { ChargeRequestSchema } from '../schemas/chargeSchema';
import { PaymentService } from '../services/paymentService';
import { IdempotencyService } from '../services/idempotencyService';

export async function chargePayment(req: Request, res: Response) {
  // Step 1: Validate against spec
  const parsed = ChargeRequestSchema.safeParse(req.body);

  if (!parsed.success) {
    return res.status(400).json({
      error_code: 'INVALID_AMOUNT', // Derive from Zod issues
      message: parsed.error.errors[0].message,
      details: parsed.error.flatten(),
    });
  }

  const { amount, currency, card_token, idempotency_key, description } = parsed.data;

  // Step 2: Check idempotency (spec requires this)
  const existing = await IdempotencyService.find(idempotency_key);
  if (existing) {
    // Spec says: return the original response, not an error
    return res.status(200).json(existing.response);
  }

  // Step 3: Process payment
  try {
    const charge = await PaymentService.charge({
      amount,
      currency,
      cardToken: card_token,
      description,
    });

    const response = {
      charge_id: charge.id,
      status: charge.status,  // 'succeeded' | 'pending' — per spec
      amount,
      currency,
      created_at: charge.createdAt.toISOString(),
    };

    // Store for idempotency
    await IdempotencyService.store(idempotency_key, response);

    return res.status(200).json(response);

  } catch (err: any) {
    if (err.code === 'card_declined') {
      return res.status(402).json({
        error_code: 'CARD_DECLINED',
        message: 'Your card was declined. Please try a different payment method.',
      });
    }

    if (err.code === 'insufficient_funds') {
      return res.status(402).json({
        error_code: 'INSUFFICIENT_FUNDS',
        message: 'Insufficient funds on the card.',
      });
    }

    return res.status(500).json({
      error_code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred.',
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

Every error_code in the catch blocks maps directly to the spec's ErrorResponse.error_code enum. If a developer tries to return 'CARD_FAILED' instead of 'CARD_DECLINED', the TypeScript types — derived from the spec — will reject it at compile time.


Step 4: Tests Are Derived From the Spec

The spec enumerates every case. Tests write themselves.

// src/__tests__/chargePayment.spec.ts
import request from 'supertest';
import { app } from '../app';

describe('POST /payments/charge — Spec Compliance', () => {
  const validPayload = {
    amount: 2500,
    currency: 'USD',
    card_token: 'tok_A1B2C3D4E5F6G7H8I9J0K1L2',
    idempotency_key: 'idem_test_key_12345678',
  };

  // ✅ Spec: 200 on valid charge
  it('returns 200 with charge_id and status on success', async () => {
    const res = await request(app).post('/payments/charge').send(validPayload);
    expect(res.status).toBe(200);
    expect(res.body).toMatchObject({
      charge_id: expect.any(String),
      status: expect.stringMatching(/^(succeeded|pending)$/),
      amount: 2500,
      currency: 'USD',
    });
  });

  // ❌ Spec: 400 when amount < 50
  it('returns 400 when amount is below minimum (50)', async () => {
    const res = await request(app)
      .post('/payments/charge')
      .send({ ...validPayload, amount: 10 });
    expect(res.status).toBe(400);
    expect(res.body.error_code).toBe('INVALID_AMOUNT');
  });

  // ❌ Spec: 400 for unsupported currency
  it('returns 400 for unsupported currency', async () => {
    const res = await request(app)
      .post('/payments/charge')
      .send({ ...validPayload, currency: 'JPY' });
    expect(res.status).toBe(400);
  });

  // ❌ Spec: 400 for malformed card_token
  it('returns 400 for malformed card token', async () => {
    const res = await request(app)
      .post('/payments/charge')
      .send({ ...validPayload, card_token: 'invalid-token' });
    expect(res.status).toBe(400);
  });

  // 🔁 Spec: idempotency — same key returns same response
  it('returns same response for duplicate idempotency_key', async () => {
    const first = await request(app).post('/payments/charge').send(validPayload);
    const second = await request(app).post('/payments/charge').send(validPayload);
    expect(second.status).toBe(200);
    expect(second.body.charge_id).toBe(first.body.charge_id);
  });

  // 💳 Spec: 402 on card decline
  it('returns 402 with CARD_DECLINED when provider declines', async () => {
    const res = await request(app)
      .post('/payments/charge')
      .send({ ...validPayload, card_token: 'tok_declineSimulator000000000' });
    expect(res.status).toBe(402);
    expect(res.body.error_code).toBe('CARD_DECLINED');
  });
});

Enter fullscreen mode Exit fullscreen mode

Every test maps to a spec statement. Code review becomes easy: "Does this test correspond to a spec requirement? Does every spec requirement have a test?"


The Payoff: What SDD Actually Gives You

🚀 Faster Onboarding

New developers read the spec and immediately understand what the system does — without reading implementation code.

🧪 Automatic Test Coverage Guidance

The spec is a checklist. If a spec item has no test, your coverage is incomplete. No guessing.

🤝 Fewer Miscommunications

When a PM asks "does it handle duplicate submissions?", you point to the spec: idempotency_key — yes, it does, here's exactly how.

🔒 Contract Stability

Frontend and backend teams can work in parallel. The API contract is defined. The frontend mocks from the spec; the backend implements against the spec. Integration becomes trivial.

📦 Tooling Bonuses

From a single OpenAPI spec you can auto-generate:

  • SDK client code (TypeScript, Python, Go...)
  • Interactive API documentation (Swagger UI, Redoc)
  • Mock servers for frontend development
  • Postman collections
  • Load test configurations

Common Pitfalls to Avoid

❌ Writing the spec after the code
This defeats the purpose. The spec becomes documentation, not a contract.

❌ Over-specifying implementation details
The spec defines what, not how. Don't put database queries or internal algorithms in the spec.

❌ Letting the spec drift from the code
Treat spec changes like code changes: pull requests, reviews, version tags. A stale spec is worse than no spec.

❌ Only developers writing the spec
If QA and product haven't reviewed it, edge cases will be missed. SDD is a team sport.


Tools to Get Started

Tool Purpose
OpenAPI / Swagger API specification format
Zod TypeScript-first schema validation
Prism Mock server from OpenAPI spec
Dredd Test API against its spec automatically
Spectral OpenAPI linting
oapi-codegen Go code generation from OpenAPI
openapi-typescript TypeScript types from OpenAPI

Conclusion

Spec Driven Development shifts the conversation from "we'll figure it out as we build" to "we've agreed on the contract, now let's build." It's not bureaucracy — it's engineering discipline that saves you from the 11pm hotfix, the post-launch confusion, and the eternal question of whose fault the bug was.

The payment module we built today had zero ambiguity from day one:

  • Every error code was named before a single catch block was written
  • The idempotency requirement was specified before anyone thought to implement it
  • The frontend team could mock the API on day one

That's the power of writing the spec first.


What about you — do you use any spec-first approaches in your team? Have you tried OpenAPI or GraphQL SDL as a contract? Let me know in the comments 👇


#softwaredevelopment #api #webdev #typescript #bestpractices