views:

115

answers:

2

I have a question about the usage of "utility/helper" methods in a factory class. Consider an example of an XML string that reprents a document. I have a class that transforms it to an "object" (say PDF, Word, CSV, etc.). I have a factory class (lets call it DocumentFactory) that accepts this XML string and based on certain rules gives back the correct document object.

My question here is that in terms of "best practices" is it ok for me to add "utility/helper" methods to the DocumentFactory class that aid in deciding that type of object will be returned? These helpers are beyond simple if/swtich case statements. But not more than 15-20 lines.

I am using one private static class as well in my code and there are about 4-5 helper methods (the helpers are public since I have tests written for these).

So is this setup a valid one for a factory class?

+1  A: 

No, there is nothing intrinsically wrong with using helper methods in a Factory to help decide what sort of object to return. All the usual method-related warnings apply, but there are no Factory-specific reasons to avoid them.

David Seiler
"All the usual method-related warnings apply"what are these?
RayJ
Nothing fancy, just what you already know if you've read your Fowler. Don't let these helper methods swell to hundreds of lines of tangled logic, avoid ordering dependencies among them, refactor them out to their own class if you find yourself wanting to use them outside the DocumentFactory. That sort of thing. If you have tests for them, and those tests are comprehensive, you're probably fine.
David Seiler
gotcha. i think i should be fine :)
RayJ
A: 

This is perfectly fine.. In fact, I'd say that using helper methods is the preferred way of doing it, since it is good practice to chunk up your code into as many re-usable methods as possible. You should probably make these helper methods private (and static, assuming the factory method itself is static).

Idris
How does one test each of the private helper methods?
Shaun F
Good point. If you need to test private methods, I guess the easiest would be to make them package methods (or just go all the way and make them public, although this is not preferred) and have the tests be in the same package as the factory class, but under the test directory rather than the src directory.
Idris
exactly what i was trying to figure out. since the utility methods are public but not intrinsic (think high cohesion) to a factory class i was considering a separate class to hold these utility methods and then use this class in the factory. however my current work place is archaic and the idea of using DI is unknown to even the development manager here. without DI i would adding unnecessary "baggage" and so i chose to put these in the Factory itself. i am glad most agree with this here :)
RayJ