Library › Coding AI › Software developers
Add input validation to a Java method with exact messages
Practice: Giving the right context. About 5 minutes.
About this exercise
QA found that createBooking accepts blank room codes, 0 nights and past dates. Add guard clauses at the top that throw IllegalArgumentException with exactly these messages: 'roomCode must not be blank', 'nights must be between 1 and 30', and 'checkIn must not be in the past'. The past-date check must use the class's clock field so tests can fix the date. Return only the updated method in exactly 1 code block of at most 20 lines, keeping the rest of it unchanged, with under 25 words of text.
Common mistakes when you ask AI for this
- Letting the AI write the messages. Tests assert on the exact message, and the AI writes its own wording. Try: Paste them: "Messages exactly: roomCode must not be blank / nights must be between 1 and 30 / checkIn must not be in the past."
- Ignoring the injected clock. LocalDate.now() reads the real date, so tests with a fixed clock can't pass reliably. Try: Add: "Use LocalDate.now(clock) with the existing clock field."
- A rewritten class. The AI reprints the class, adds a validator helper or switches to Bean Validation annotations. Try: Add: "Return only createBooking, guards at the top, the rest unchanged."
- An explanation of every check. The AI explains each guard and suggests extra ones. Try: Add: "One code block, no text."
What a strong prompt includes
- Gives the exact messages
- Mentions the clock
- Names the exception
- Asks for only the method
- Protects the existing code
Related exercises
- Add a cron line that matches the others in a crontab (Coding AI · Product managers)
- Add dark mode by overriding your existing CSS variables (Coding AI · Software developers)
- Add input checks to your number guessing game (Coding AI · High school students)
- Add labels to a signup form without rewriting the page (Coding AI · High school students)
- Add mail-merge greetings for couples and missing names (Coding AI · Nonprofit staff)