Java – Avoiding Factory Pattern While Managing Complexity

design-patternsjava

Factory pattern (or at least the use of FactoryFactory..) is the butt of many jokes, like here.

Apart from having verbose and "creative" names like RequestProcessorFactoryFactory.RequestProcessorFactory, is there anything fundamentally wrong with the factory pattern if you have to program in Java/C++ and there is a usecase for Abstract_factory_pattern?

How would another popular language (for example, Ruby or Scala) avoid having to use it while managing similar complexity?

The reason I am asking is I see mostly the criticism of factories mentioned in the context of the Java/Java EE ecosystem, but they never explain how other languages/frameworks solve them.

Best Answer

Your question is tagged with "Java", no surprise you're asking why is the Factory pattern being mocked: Java itself comes with a nicely packaged abuses of that pattern.

For example try loading an XML document from a file and run an XPath query against it. You need something like 10 lines of code just to setup the Factories and Builders:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder(); 

Document xmlDocument = builder.parse(new FileInputStream("c:\\employees.xml"));
XPath xPath =  XPathFactory.newInstance().newXPath();

xPath.compile(expression).evaluate(xmlDocument);

I wonder if the guys designing this API ever worked as developers or did they just read books and throw things around. I understand they just didn't want to write a parser themselves and left the task to others but it still makes for an ugly implementation.

Since you're asking what's the alternative here's loading the XML file in C#:

XDocument xml = XDocument.Load("c:\\employees.xml");
var nodes = xml.XPathSelectElements(expression);

I suspect newly hatched Java developers see the Factory madness and think it's OK to do that - if the geniuses who built Java themselves have used them that much.

Factory and any Other patterns are tools, each suited for a particular job. If you apply them to jobs they aren't suited for you're bound to have ugly code.