Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have seen this at many places. a Parent class has a static method to create objects of the right subclass and at times we have a dedicated factory class with instance methods to create object of various subclasses.

Which one is used in which scenario ?

Like static factory methods of InetAddress in to create subclasses of InetAddress Vs BorderFactory class to create various Borders.

share|improve this question
Needing to modify the parent class when creating a new derived class is a poor code smell. – James Youngman Mar 19 '12 at 11:28
up vote 5 down vote accepted

The second one; the separate class. That separate class should also have an interface. The reason is that this is the option that allows swapping the factory most easily, which is good for lowering coupling and for testability.

share|improve this answer
It might also be worth looking at Inversion of Control, or actually its close cousin Dependency Injection which some argue is a cleaner, more pluggable way to get the same behaviour. – Martijn Verburg Mar 19 '12 at 9:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.