intermediateFactory Method Pattern

Why should a factory method throw an exception for an unrecognized type instead of returning null?

Returning null for an unrecognized type defers the failure to whatever code eventually tries to use the returned object, which typically surfaces as a NullPointerException somewhere far from where the actual mistake, an unsupported type string, was made. Throwing immediately, with a message that names the specific unsupported type, fails loudly and precisely at the actual point of the problem, which is dramatically easier to debug. The general principle is to fail as close to the actual bad input as possible, rather than letting a bad value propagate silently until it causes a confusing symptom somewhere else in the call stack.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to Why is a builder for a class commonly implemented as a static nested class rather than a separate top-level class?← Back to all Low-Level Design & Design Patterns questions