Field SOP
Field SOP

General Coding Prompt Pack: Write, Refactor, Explain, and Generate Code

A three-level general coding prompt pack: beginner function generation, intermediate refactor and optimization, expert system design and multi-file scaffolding. Includes a cheatsheet prompt. Constraints: runnable, edge cases, no fabricated APIs, human review required.

Published August 2, 20265 min read
<!-- prompt-coding-pack | resource | General Coding Prompt Pack: Write, Refactor, Explain, and Generate Code -->

AI doesn't lack speed when writing code, it lacks "getting it right." The usual wrecks: you ask it to "write a parser function," it hands back a call to an API that doesn't exist; you say "refactor this," it rewrites the whole thing and silently changes behavior; you ask it to "design a module," it draws an empty skeleton you can't build on. The problem isn't model capability, it's that the prompt never pinned down the constraints.

This site already has the Code Review and Debug Prompt Pack, which handles "code is written, now find the problems"--bug locating, pre-commit review, and refactoring directions surfaced during a review. This is its companion, covering the four scenarios where code is "not yet written, or written but needs surgery": generate a function from a requirement, refactor and optimize, design a system scaffold, and speed-read unfamiliar code. The two don't overlap: that one is review and debugging, this one is generation and modification. Specifically, that pack's refactoring step "surfaces maintainability issues during review and points a direction"; this pack's refactoring takes runnable code and forces out smells, complexity, and performance problems into an execution plan with dependency ordering and preserved behavior. It's hands-on, not diagnostic.

Four prompts in three escalating tiers, plus a speed-reading cheatsheet. Each has a role, task, constraints, and output format, with variables marked {{}}. Copy and adapt.

Beginner: Generate a Function from a Requirement

The most expensive mistake in writing code is "starting before the requirement is aligned." The AI defaults to dumping a full implementation from a vague prompt, making your decisions for you about parameter types, error handling, and return shape. By the time you notice it's wrong, you're starting over. The core of this step is "signature first, implementation second," turning a one-shot generation into a two-turn dialogue: align the contract, then build.

Prompt
You are a senior {{language}} engineer. Implement a function per the following requirement, in two steps. Do not write the full implementation in one go.

Requirement: {{requirement description + language}}

Step 1 -- Function signature and contract (write only this, wait for my confirmation before implementing)
- Function name, parameters (with types), return type
- For each input, list the valid range and boundary values (null / empty string / 0 / negative / oversized / huge)
- List every exception or error condition to handle, and state whether it throws or returns an error code
- Do not write the implementation logic

Step 2 -- Implementation (after I confirm the signature)
- Implement per the confirmed signature, including all boundary handling
- Use only the {{language}} standard library or third-party libraries I name explicitly; do not invent any API that doesn't exist. If unsure whether an API exists, mark it "to verify"
- No filler comments (like "process the data here" or "// loop through items"); explain why only where it's non-obvious
- Append 3 call examples at the end: one normal input, one boundary input, one error input, each with the expected return value

Constraints: if the requirement is ambiguous, list the ambiguities and ask me; do not assume. Code must run directly with no TODO placeholders.

Key point: the two-turn structure is the soul of this prompt. The bug I hit most is letting the AI produce a full implementation in one shot--it defaults to returning null for "record not found" when my caller expects an exception. Lock the signature and error contract first, then implement, and that rework vanishes. The "3 call examples" also matter: the AI claims it handled boundaries, but forcing it to write out the boundary input's expected return is how you catch that it actually didn't.

Intermediate: Refactor and Optimize

Code runs, but it's slow, tangled, or hard to maintain. Telling the AI "refactor this" is the most dangerous instruction: it rewrites everything, quietly changes behavior (different error handling, off-by-one at the boundary, dropped side effects), and you only find out in production. This step splits refactoring into "diagnosis -> plan -> key snippet," and forces "preserve behavior + order dependencies + mark uncertain as to-verify."

Prompt
You are a refactoring expert. Analyze the following code, identify issues, and produce an executable refactoring plan.

Code:
{{code}}

Output in this structure:

1. Problem diagnosis (ordered by severity, high to low)
   - Code smells: long function / duplication / deep nesting / large class / divergent change, etc. For each, point to the specific line or snippet
   - Complexity: functions with high cyclomatic complexity, with a rough estimate and why it's excessive
   - Performance: N+1 queries, unnecessary repeated computation, loops that can drop a degree (O(n^2) -> O(n)), sync blocks that could be async
2. Refactoring plan
   - Each problem maps to one independent refactoring action (extract function / inline / introduce parameter object / decompose conditional / substitute algorithm, etc.)
   - For each action: what to change, why, and the concrete payoff (specific improvement to readability / performance / testability)
   - Mark dependency order between actions (which must go first or later actions can't proceed)
3. Refactored key snippets
   - Show only the changed parts, with comments marking before/after (e.g., `// old: ... new: ...`)
   - Public interface signatures stay unchanged; if a change is necessary, list it separately with a reason

Constraints: do not rewrite parts not involved; if you're unsure something is a problem, mark it "to verify" rather than changing it; refactored behavior must be equivalent to the original, with 2-3 verification ideas (e.g., "given [empty input], original returns X, refactored must return X").

Key point: unlike review-oriented refactoring suggestions, this prompt wants "an execution plan you can commit step by step," so "dependency order" and "behavior-equivalence verification" are hard constraints. The AI's favorite mistake is confidently changing what it shouldn't--say, silently turning "return -1 when not found" into "raise ValueError"--so the "to verify" tag is safer than a direct edit. The performance column is the deliberate differentiator from the review pack: that one watches maintainability, this one additionally forces out complexity numbers and performance downgrade opportunities.

Expert: System Design and Multi-File Scaffolding

A single function is easy; a module is hard. The AI's chronic disease in module design is "over-layering"--regardless of requirement size, it stacks repository / service / factory / facade / DTO, building layers the current need never uses. This step forces "minimal directory structure" and "interfaces concrete down to types," producing a scaffold you can build files against directly.

Prompt
You are a systems architect. Based on the following module requirement, produce a scaffold design that can be built directly.

Module requirement:
{{module requirement}}

Output:

1. Directory structure
   - List files and directories as a tree, annotating each file's responsibility in one sentence
   - Separate into entry / core logic / data layer / utility layer / tests
   - Build only the layers the current requirement actually uses; do not pre-build unused layers, and at the end explain "why layer X is not built"
2. Interface definitions
   - List interfaces the module exposes (functions / classes / API endpoints)
   - For each: signature, input param types, return type, errors it can throw
   - Types must be concrete; no vague words like "relevant data" or "config object," use concrete structures or type names
3. Key implementation notes
   - Pick 2-3 core functions and give implementation skeletons (target-language snippets or structured pseudocode)
   - For each technical choice, explain in one sentence why X over Y
4. Testing strategy
   - Unit tests: list case outlines for core functions, at least 1 positive + 2 negative (bad input / boundary) per function
   - Integration tests: list verification points for inter-module interaction
   - Mark which tests should be written first (which lock down behavior fastest)

Constraints: minimize the directory structure; do not introduce abstraction layers the requirement doesn't mention; interface definitions must be concrete down to types; do not invent third-party library APIs--when using a third party, name the library and version range.

Key point: "why layer X is not built" is a brake I added. The AI hands you a full scaffold by default; forcing it to explain "why a repository layer isn't needed here" is how it admits the current scale doesn't call for one. "Concrete down to types" works the same way--the AI loves writing config: object, a useless type; force it to config: { retries: number; timeout: number } and you can build a file from it. "Which tests lock down behavior first" turns the test strategy from a list into a prioritized plan, so you don't write a pile of tests that miss the core path.

Cheatsheet: Read Unfamiliar Code in 5 Minutes

Not every scenario is about writing new code. Taking over a legacy project, reading open-source source, reviewing someone's PR--the core need is "get what this does, fast." Asking the AI to "explain this code" gets you line-by-line translation, lots of words, no signal. This cheatsheet forces a structured five-part output: function -> entry -> data flow -> hard part -> side effects, capped at 3 lines each.

Prompt
You are a technical mentor. Help me understand the core logic of the following unfamiliar code in 5 minutes.

Code:
{{code}}

Output in this structure, max 3 lines per section:
1. What it does: one sentence on the overall function, no implementation details
2. Where it starts: mark the entry point or main function (line number or function name)
3. How data flows: input -> key transformations -> output, arrow-chain the main path, skip branches
4. The tricky part: point out 1-2 hardest-to-read spots, explain in plain language, don't copy code
5. Dependencies and side effects: what external state / modules / globals it relies on, what external state it mutates

Constraints: do not translate line by line; do not judge the code, only state "what it does"; if you can't trace a part, say "need more context" honestly, don't fabricate an explanation.

Key point: "how data flows" is the fastest handle for understanding code--ten times faster than reading line by line. The AI defaults to line translation ("line 10 declares x, line 11 checks x"), which says nothing. "Say 'need more context' honestly" is the critical brake: the AI will confidently fabricate a plausible explanation for code it can't actually trace; forcing it to admit it can't follow tells you where to dig in yourself. I use this prompt daily to read npm dependency source and decide in five minutes whether a snippet is usable.

Four Standing Constraints

The four prompts above share four hard constraints. They are the floor for "whether AI-written code is usable":

  1. Runnable + boundary handling: output code must run directly, with no // TODO placeholders; boundaries (null, empty array, oversized input, concurrency) must be handled explicitly, not waved off with "assume valid input" in a comment.
  2. No fabricated APIs: the number-one cause of AI coding wrecks. It will confidently write lodash.deepMerge(), axios.retry()--calls that look reasonable but don't exist. Allow only the standard library or named libraries; mark anything uncertain "to verify."
  3. AI draft vs. human review: every prompt's output is a draft, not a finished product. No matter how strong the model, code must be reviewed and tested by a human before production. The prompts ask for "verification ideas" and "call examples" to give the human reviewer a handle, not to let the AI self-certify.
  4. De-AI the output: ban filler comments ("process the data here"), demand specifics on why; ban throat-clearing ("as we all know"); require concrete type names instead of "object" or "relevant data." AI-flavored code looks tidy but carries no information.

How to Use

The four prompts aren't a linear pipeline; pick by scenario:

  • Writing a new function: use the beginner prompt. Get the signature and contract first, confirm boundaries and error conventions, then let it implement.
  • Changing old code: use the intermediate prompt. Run the diagnosis, commit actions one at a time in dependency order, run a behavior-equivalence check after each commit.
  • Building a new module: use the expert prompt. Get the directory and interfaces first, build file skeletons against them, then fill in implementations.
  • Reading unfamiliar code: use the cheatsheet. Get the main path in five minutes, decide whether to read deeper.

Model choice: the beginner function-generation prompt is low-bar; mainstream models handle it, with DeepSeek offering good cost-performance for batch generation. Intermediate refactoring and expert system design lean reasoning-heavy, where Claude Opus / GPT-5 / Codex-class coding-tuned models are more reliable, and Claude's long context suits feeding an entire module's code in for refactoring. The cheatsheet is low on reasoning; both Claude and DeepSeek work. One line: pick DeepSeek for everyday generation, Claude / GPT-5 for surgery and design.

Pitfalls

  1. Asking for the full implementation in one shot: the AI locks in parameter types and error handling for you, and you rebuild when it's wrong. Fix: the beginner prompt forces two turns, signature before implementation.
  2. The AI fabricates APIs: it writes someLib.doTheThing() with full confidence, and the method doesn't exist. Fix: allow only the standard library or named libraries, mark uncertain ones "to verify," and run it to find out.
  3. Refactoring silently changes behavior: the AI turns "return -1" into "raise an exception," or sync into async, and behavior drifts. Fix: force "behavior equivalence + verification ideas," and run tests after every independent commit.
  4. Scaffold over-layering: the AI stacks repository / service / factory wholesale when the current need calls for two layers. Fix: force "minimal directory" + "explain why layer X isn't built."
  5. The AI fabricates explanations for code it can't follow: it invents a plausible-sounding reading, you believe it, you get burned. Fix: the cheatsheet forces "say 'need more context' when you can't trace it."

References

This article is AI-assisted and human-edited. Last updated: 2026-08-02

Related

Field SOP

User Research & Interview Prompt Pack: From Outline to Persona

A three-level user research & interview prompt pack: beginner semi-structured interview outline (anti-leading-questions), intermediate single-transcript structured insights (quote-tagged, no fabrication), expert N-transcript cross-sample synthesis into personas + JTBD + opportunity map (affinity mapping, frequency counts, conflict flagging). 4 general constraints (anti-fabrication/de-identification/human review) and 5 pitfalls.

Aug 4, 20265 min read
Field SOP

Code Testing Prompt Pack: Unit, Parameterized, E2E & Refactor

A three-level code testing prompt pack: beginner generates unit tests per function (signature and boundary list first, N cases each for normal/boundary/error, pytest/jest parameterized), intermediate parameterized batch cases with a test plan (coverage gaps, minimal mocking), expert integration/E2E strategy and test refactor (test pyramid, contract tests, redundancy pruning). Includes a 5-minute cheatsheet. Anti-fabrication constraints embedded (no invented APIs, no fabricated coverage numbers). Differentiated from the general coding and review/debug packs--this one handles writing tests only.

Aug 4, 20265 min read