Generating Code with ChatGPT
Generating Code with ChatGPT
ChatGPT can produce a surprising amount of working code, but only when you describe the result precisely and check the output. Treat generation as pair programming with a fast, sometimes wrong, assistant.
Describe the Behavior, Not Just the Name
Name the function, the inputs, the outputs, and the edge cases. A prompt such as "write a factorial function" is fine for a toy; a prompt that lists the base cases, the error behavior, and the input type is what you would actually ship.
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
print(factorial(-1))Ask the model to walk through the code line by line afterwards. That exercise exposes cases the author (or the model) forgot.
Ask for Idiomatic Code
State the target language, version, and style. Java 8 differs from Java 21, and Python 2 code will not run today. Mention libraries you are allowed to use. Otherwise the model picks defaults that may not match your project.
Request Tests as Part of the Answer
The strongest pattern is to ask for code and its tests in one request. The model then writes the implementation against the expectations it stated; mismatches become visible immediately.
import unittest
class TestFactorial(unittest.TestCase):
def test_base_case(self):
self.assertEqual(factorial(1), 1)
if __name__ == "__main__":
unittest.main()Run the tests in your own environment. A passing test suite is the only real verification; a model saying "this code works" is not.
Key Points
- Describe behavior, inputs, outputs, and edge cases.
- Pin the language and version in the prompt.
- Ask for tests alongside the code.
- Run the code and tests before trusting the answer.