Editorials

Why Use a Factory?

Happy New Years!
I’d like to wish each of you a happy new year. I wish for all of you success as you strive to perfect your craft using computers and software to fulfill your business goals. Remember, you alone are responsible for your continued education. Your employer may provide assistance as a benefit…but you are the one who can take control and reach for more!

Why Use a Factory?
Different books on object oriented patterns perceive a factory as either an independent pattern or a principle for implementing other patters. I have found a number of reasons to use a factory, regardless of how it is classified.

Simply, a factory may be defined as a class whose purpose is to instantiate another class, with the intention to encapsulate the rules of instantiation from the client consumer. A client calls the factory providing necessary input parameters, and the factory does all the heavy lifting of instantiation.

There is a bit of work to creating and implementing a factory class. So, should I always use a factory to instantiate a class? If not, when should I consider using a factory? Here are some questions I ask myself when considering if I should create a factory?

  • Could/Will/Do I instantiate this class in multiple places?
  • Are there decisions that must be implemented when instantiating a class?

If any of these questions are true, there is a strong probability I will use a factory to instantiate a class. Let’s demonstrate the value of this principle with a real world example.

Let’s say you have a class for user access in your system. The class handles authentication (am I who I say I am) and authorization (what can I do once I am authenticated). Many systems may have multiple entry points in which user access must be implemented. This is already a case where a factory should be considered.

Later on, your business analysts determine further requirements for your user access class. They have determined that the class must be able to enforce certain hours of access (a user may use the system between 8:00AM and 5:00PM). In addition, they wish to support authentication from external sources such as facebook. If you are using a factory, it is much easier to add these additional requirements because the new branching requirements are more easily implemented in a factory.

Are you an OO guru? Drop a note to btaylor@sswug.org to share your insight into the benefit of a factory and why you like to use them. Can they be overused? Let us know.

Cheers,

Ben

$$SWYNK$$

Featured White Paper(s)
Top 10 Tips for Optimizing SQL Server Performance
read more)