When is a factory the right answer, when is a builder, and when should you just call the constructor?
Answer
Short answer
A constructor is the default and needs no justification.A static factory earns its place when construction can return a cached or alternative implementation, or needs a name; a builder when there are many optional fields.
Keep creational patterns explicit in the answer because that is the concept the interviewer is actually trying to test. A good creational patterns explanation names the trade-off, the failure mode, and the evidence you would use before choosing. Use creational patterns once more at the decision point so the answer reads as judgement rather than a detached example.
Keep creational patterns explicit in the answer because that is the concept the interviewer is actually trying to test. A good creational patterns explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- How would you make a builder reject an object missing a required field at compile time?
- What does a dependency-injection container give you that a singleton does not?
- Why is an enum the safest way to implement a singleton in Java if you must have one?
- When does a factory method belong on the type it creates, and when does it belong on a separate class?
Related questions
- How would you implement a singleton, and why do many teams treat it as an anti-pattern?mediumAlso on singleton and creational-patterns4 min
- How would you design a ledger so that any balance can always be proved?hardAlso on immutability5 min
- How would you design a thread-safe component, and why is adding synchronized to every method not a design?hardAlso on immutability7 min
- Messages arrive with a type field and each type needs a different object built to process it. How do you design the creation so you do not end up with a growing switch statement?mediumAlso on factory6 min