Library › Coding AI › Software developers

Refactor nested null checks into an Optional chain

Practice: Setting limits and rules. About 5 minutes.

About this exercise

Refactor cityLabel into a single Optional chain with no if statements or null checks. Product also wants blank or whitespace-only cities treated like missing ones, and the fallback text is now exactly 'Unknown city' (not 'N/A'). Clean the city with strip(), not trim(), because the old CRM sends Unicode spaces. Keep the signature. Return only the method in exactly 1 code block of at most 9 lines, under 20 words of text.

Common mistakes when you ask AI for this

  • Missing the blank case. A straight conversion still returns " " for blank cities, and trim() misses Unicode spaces. Try: Add: "map(String::strip) and treat blank as missing."
  • The old fallback. The AI keeps "N/A" because that's what the code says. Try: Add: "Fallback exactly 'Unknown city'."
  • Half a refactor. The AI may keep an if or a null check around the chain. Try: Add: "One Optional chain, no ifs or null checks."
  • The whole class and a lecture. The AI reprints the class and explains Optional. Try: Add: "Only the method, one code block, no text."

What a strong prompt includes

  • Asks for an Optional chain
  • Handles blank cities
  • Gives the new fallback
  • Protects the signature
  • Asks for only the method

Practice this now ↑

Related exercises