When To Use a Factory

All too often I see people creating factory or factory methods for objects that could have just as easily been created by their constructor.

The factory pattern is meant to encapsulate the complexity of object creation. If the creation process is not complex, there is little need for a factory.

Here is one example I see quite often:

	class WidgetFactory
	{
		public static Widget Create()
		{
			return new Widget();
		}
	}

In this case, the factory is completely unnecessary. I would venture to say that the following is likewise unnecessary:

	class WidgetFactory
	{
		public static Widget Create(string name, int size, string description)
		{
			Widget widget = new Widget();
			widget.name = name;
			widget.size = size;
			widget.description = description;

			return widget;
		}
	}

In this case, a constructor could have easily taken care of creating this object. So what kind of class needs a factory? The answer is any class that has complex creation. Here is a good example:

	class WidgetFactory
	{
		public static Widget FromString(string widgetExpression)
		{
			WidgetExpressionParser parser = new WidgetExpressionParser();
			WidgetBuilder builder = new WidgetBuilder();
			Widget newWidget = builder.ConstructWidgetFromParsedTree(parser.Parse(widgetExpression));
			return newWidget;
		}
	}

Because constructing this object is pretty complex, it is good to hide the complexity behind a factory. Factories are not bad, but they are often overused. Any time you use a pattern, make sure there is a compelling reason to use it. If you are unsure why you are using a pattern, it is very possible that you are not using it right. Never use a pattern just for the sake of using a pattern.

-=CE=-

This entry was posted in Design, Patterns and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*
*