The Factory pattern


I am currently whacking through some code to update an application. This is a normal part of life for the developer. In the code, however, I found the following method:

ServiceFactory.GetSim(...)

This may not cause any flags to fly intially, but the factory is designed to return an instance of a service. Did that one hit you?

If not, let me explain. The Factory pattern, in object oriented programming, is similar to a real world factory. When you go to a real world factory, they create products. When you code using a factory method, you return objects. If you want to be completely anal, you would have an abstract factory with at least one concrete factory. Regardless, the job of the factory is to return objects.

Okay, so this method returns SIM objects. What is wrong with that? Easy. It is not a SIM factory, it is a service factory. The proper use of the factory is to return a service instance. When you start munging it up with other types of factory calls, you muddle the code. It would be like calling the UPS and asking for some Purina dog chow. While USP might be the service that delivers the dog chow, they do not manufacture it. In the same manner, a service factory (UPS) should not have methods for returning SIMs (dog chow).

Yes, this may seem a bit overboard, but I am currently trying to duplicate a pattern and I find it completely obfuscated in the code. UPS might be able to deliver anything I ask them, by placing the order (if they had that service), but it is better for me to call Purina directly after arranging shipping. Yes, the analogy sucks, but it got you thinking.

Until next time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: