Write Prompts That Get You Better Code
Write Prompts That Get You Better Code
The quality of a ChatGPT answer is bounded by the quality of the prompt. A vague request produces vague output; a precise request produces usable output. The practical difference comes from four habits: context, constraints, format, and examples.
Give Context First
Tell the model who is asking and why. Start with a sentence that sets the scene, such as the language, framework, and level of the reader. The model cannot guess these details, so never make it guess.
Add Constraints and Format
State what must be true in the answer: supported versions, no external libraries, error handling, or a specific structure. When you need a list, ask for a list. When you need code, ask for code and say which language and which API version.
Use the System and User Split
The API separates a system message from a user message. The system message sets behavior once; the user message carries the request. This keeps the tone consistent across many calls.
messages = [
{"role": "system", "content": "You are a senior Java developer."},
{"role": "user", "content": "Write a Java method that reads a CSV file, returns a list of rows, and skips the header row."}
]Note the careful prompt: it names the language, the input, the expected output type, and a subtle edge case (the header row).
Iterate on the Prompt
Treat prompting as debugging. If the answer misses the point, rephrase and add one missing constraint rather than repeating the same request. Keep a small library of prompts you reuse, and parameterize them for the API.
Key Points
- Context before request: language, framework, and audience.
- Constraints prevent wrong assumptions.
- Request an explicit format and code style.
- Iterate prompts, do not repeat them.