Make a Builder That Can't Build Too Early

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write a class RequestBuilder for an HttpRequest (a url, a method of GET, POST, PUT or DELETE, and headers). Start with new RequestBuilder(); url(url), method(method) and header(name, value) each return a new builder with that part set, leaving the one they were called on unchanged, and build() returns the request, with headers {} if none were set. build() must only compile once both url and method have been set, in any order: track what has been set in the builder's type parameter. At runtime build() still throws if either is missing, for callers without types.

Your code must pass

  • Builds the request with its headers
  • Each step returns a new builder
  • build throws when url or method is missing
  • Has no type errors
  • build needs a url and a method
  • Builds once both are set, in any order
  • Rejects an unknown method