April 24, 2007 Leave a comment
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:
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.