With the rising popularity of AI programming tools, a crucial concept is reshaping how we collaborate with AI to write code—SDD (Specification-Driven Development). This article will delve into the core philosophy of SDD and why mainstream AI programming tools are choosing to support the SDD model.

What is SDD

Definition of SDD

Specification-Driven Development (SDD) is a software development methodology that emphasizes writing clear, precise specifications before writing code, and then strictly implementing code according to those specifications.

Core Principles:

  • Spec First: A Spec must be written before code implementation.
  • Precise Description: Use formal or semi-formal languages to describe requirements.
  • Bidirectional Traceability: Specifications and code remain consistent and can be verified against each other.
  • Iterative Refinement: Start with a simple specification and gradually refine and improve it.

SDD vs Traditional Development Models

Dimension Traditional Development SDD
Starting Point Requirement documents or verbal descriptions Precisely written Spec files
Flexibility Requirements change while writing Implementation after specification confirmation
Verification Mainly manual testing Specifications serve as test cases
AI Collaboration AI has broad creative freedom AI executes according to specifications
Change Handling High cost of requirement changes Specification changes drive code modifications

Why AI Programming Needs SDD

Challenges in AI Programming

1. Context Understanding Bias

Although AI models are powerful, they cannot fully understand ambiguous human descriptions. Requirements in traditional development are often like:

"Implement a user login function with basic validation"

Such ambiguous descriptions lead to AI-generated code that does not match expectations.

2. Unstable Generated Code Quality

Without specification constraints, AI might:

  • Miss handling of edge cases
  • Ignore security considerations
  • Have inconsistent API design styles
  • Implement code inconsistent with the existing project style

3. Difficult Iteration and Maintenance

When AI generates code without specifications:

  • It is hard to judge if requirements are met
  • The scope of impact is unknown during modifications
  • It is difficult for new team members to understand the design intent

How SDD Solves These Problems

Specifications Provide Precise Intent

# Traditional requirement description
"Implement a user login function"

# SDD specification description
## Functional Requirements
1. Support username/email + password login
2. Generate JWT token upon successful login, valid for 24 hours
3. Lock account for 15 minutes after 3 incorrect password attempts
4. Login interface requires brute-force protection (Rate limiting: max 10 attempts per IP within 5 minutes)

## Interface Specification
- POST /api/v1/auth/login
- Request: { "username": string, "password": string }
- Response: { "token": string, "expiresIn": 86400 }

## Error Handling
- 400: Parameter validation failed
- 401: Username or password incorrect
- 423: Account locked

## Security Requirements
- Use bcrypt for password storage
- Returned token must not contain sensitive information

Specifications as Test Cases

SDD specifications can be directly or tool-converted into:

  • API Mock tests
  • Unit test cases
  • Integration test scenarios
  • Acceptance criteria

Value of SDD in AI Programming

1. Reduce Hallucinations

When constrained by clear specifications, AI is more likely to generate code that meets expectations rather than “creating” non-existent features.

2. Improve Code Consistency

Specifications define unified:

  • API design styles
  • Code organization structure
  • Naming conventions
  • Error handling patterns

3. Facilitate Review and Collaboration

The clarity of specifications allows:

  • Code reviews to be based on evidence
  • Team members to work in parallel
  • New members to quickly understand the project

4. Support Progressive Development

SDD supports starting with a simple specification and gradually expanding it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# v1.0 Minimum Viable Version
## AuthService
- login(username, password): Promise<User>

# v1.1 Add token support
## AuthService
- login(username, password): Promise<LoginResult>
- logout(token): Promise<void>
- refreshToken(token): Promise<LoginResult>

# v1.2 Add third-party login
## AuthService
- login(username, password): Promise<LoginResult>
- loginWithOAuth(provider, code): Promise<LoginResult>
- logout(token): Promise<void>
- refreshToken(token): Promise<LoginResult>

Core Components of SDD

1. Spec File Structure

project/
├── SPEC.md              # Main specification file
├── api/
│   └── openapi.yaml     # API specification
├── models/
│   └── schema.md        # Data model specification
└── specs/
    ├── auth.md          # Authentication module specification
    ├── user.md          # User module specification
    └── ...

2. Specification Writing Principles

FIRRN Principles:

  • Factual: Describe the actual behavior of the system, not a wish list.
  • Independent: Each specification module describes one function independently.
  • Readable: Specifications should be easy to understand and maintain.
  • Realistic: Specifications must be achievable and testable.
  • Necessary: Every requirement is necessary.

3. Mapping Specifications to Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
## UserService.getUserById

### Description
Get user information by user ID

### Input
- userId: string (Required, User ID)

### Output
- User object or null

### Behavior
1. Validate userId format
2. Query user from database
3. Return user information (password field excluded)

### Errors
- InvalidUserIdError: userId format is invalid

Corresponding code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
async getUserById(userId: string): Promise<User | null> {
  // 1. Validate userId format
  if (!isValidUserId(userId)) {
    throw new InvalidUserIdError(userId);
  }

  // 2. Query user from database
  const user = await this.db.users.findOne({
    where: { id: userId },
    attributes: { exclude: ['password'] }
  });

  // 3. Return user information
  return user;
}

SDD Workflow

Complete Development Process

┌─────────────────────────────────────────────────────────┐
│  1. Requirement Analysis                                 │
│     - Collect business requirements                       │
│     - Identify key use cases                              │
│     - Determine constraints                               │
└───────────────────────┬─────────────────────────────────┘
                        ▼
┌─────────────────────────────────────────────────────────┐
│  2. Write Spec (Specification)                           │
│     - Write SPEC.md                                       │
│     - Define API interfaces                               │
│     - Describe data models                                │
│     - Clarify boundary conditions and error handling     │
└───────────────────────┬─────────────────────────────────┘
                        ▼
┌─────────────────────────────────────────────────────────┐
│  3. Review and Confirmation                               │
│     - Technical review                                   │
│     - Business confirmation                               │
│     - Lock specification after consensus                 │
└───────────────────────┬─────────────────────────────────┘
                        ▼
┌─────────────────────────────────────────────────────────┐
│  4. AI Generates Code                                    │
│     - Generate code based on Spec                         │
│     - Generate unit tests                                 │
│     - Generate API documentation                          │
└───────────────────────┬─────────────────────────────────┘
                        ▼
┌─────────────────────────────────────────────────────────┐
│  5. Verification and Iteration                            │
│     - Does code conform to Spec?                         │
│     - Is test coverage complete?                         │
│     - Update Spec or fix code when issues are found      │
└─────────────────────────────────────────────────────────┘

Spec Review Checklist

  • Functional description is clear and unambiguous
  • Inputs and outputs are clearly defined
  • Boundary conditions are covered
  • Error handling is complete
  • API design is consistent
  • Data model is reasonable
  • Security considerations are comprehensive
  • Performance requirements are clear

SDD Tool Ecosystem

Mainstream SDD Tools

Tool Features Use Cases
Spec-Kit Designed for AI programming, CLI tool Claude Code integration
OpenSpec Open standard, community-driven Cross-tool universal
Stopify Simple Markdown format Lightweight projects
Docusaurus Documentation-driven Projects with mature documentation

Claude Code and SDD

Claude Code natively supports the SDD workflow:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 1. Create project and write specification
mkdir my-project && cd my-project
claude "Initialize a Node.js REST API project, create SPEC.md specification file"

# 2. Implement based on specification
claude "Implement the user authentication module according to SPEC.md"

# 3. Verify if implementation conforms to specification
claude "Check if the current implementation fully conforms to the definitions in SPEC.md"

# 4. Sync modifications when specification updates
# Edit SPEC.md to add new features
claude "Refactor related code according to the updated SPEC.md"

SDD Best Practices

Specification Writing Tips

1. Use Structured Format

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
## Function Name

### Description
Brief description of what the function does

### Input
- param1: type (description)
- param2: type (description)

### Output
- type: description

### Behavior
1. Step 1
2. Step 2

### Errors
- ErrorType: description

2. Use Concrete Examples

### Login Success Example
Input: { "username": "user@example.com", "password": "correct_password" }
Output: { "token": "eyJhbGciOiJIUzI1NiIs...", "expiresIn": 86400 }

### Password Error Example
Input: { "username": "user@example.com", "password": "wrong_password" }
Output: 401 { "error": "INVALID_CREDENTIALS", "message": "用户名或密码错误" }

3. Define Clear Acceptance Criteria

## Acceptance Criteria
- [ ] Username format validation is correct
- [ ] Password strength validation is correct
- [ ] Valid token returned on successful login
- [ ] Error count statistics are correct
- [ ] Account locking function works normally
- [ ] Token expiration handling is correct

Common Pitfalls

1. Specifications Are Too Detailed

1
2
3
4
5
6
7
# Bad practice: Dictating code implementation details
### Implementation
Use a for loop to iterate through the array, call the helper function on line 5

# Good practice: Only describing behavior
### Implementation
Process data items in the specified order

2. Specifications and Implementation Are Out of Sync

  • Update the Spec every time code is updated.
  • Spec changes must go through review.
  • Forbid “code implemented but Spec not updated”.

3. Over-abstraction

Specifications must be concrete and executable, not vague architectural designs.

Summary

Core Value of SDD

  1. Clarity: Eliminates ambiguous requirements and reduces communication costs.
  2. Verifiability: Specifications can be directly converted into test cases.
  3. Maintainability: Code and documentation always remain consistent.
  4. AI-Friendly: Provides clear execution goals for AI.

SDD Applicability Scenarios

Scenario SDD Suitability Reason
AI-assisted programming Very Suitable AI needs clear instructions
Complex business systems Suitable Reduces requirement understanding deviations
Rapid prototyping Average Specifications might become a burden
Personal small projects Optional Over-design might be wasteful
Multi-person collaborative projects Very Suitable Unified understanding and standards

Learning Suggestions

  1. Start with Small Projects: Choose a simple project to practice the SDD workflow.
  2. Use Good Tools: Recommend starting with Spec-Kit or simple Markdown.
  3. Keep Specifications Updated: Specifications are not one-time; they require continuous maintenance.
  4. Collaborate with AI: Let AI help you generate the specification draft, and you review and refine it.

SDD is not a silver bullet, but it provides a reliable framework for AI programming. As AI programming tools continue to evolve, SDD will become an important foundation for efficient human-computer collaboration.