[snip of java code]
> I forgot... Why is this ugly reflective mess that drops exception
> details and instantiates arbitrary classes "most maintainable"? Smells
> kinda bad to me. I hope theres a good reason for this thing.
Have you ever done a factory method before without reflection? It's a
big, uglier "if" statement with hard-coded class names - smells like
hard-coded methods crying for polymorphism. If that approach is more
maintainable, I don't see how, but I'm willing to listen to your
explanation.
Although a big if statement with "new" statements may be more readable,
adding support for a new sub-class is harder to maintain, because you
have to add the new if/then statement with the instantiation. If your
saying ultimately that the factory method design pattern is what's
harder to maintain, then maybe that's because design patterns are always
less obvious to those who've never seen them. The beauty of the approach
proposed here is that you simply create the new XyzProduct class and
drop it into the package. No code in the factory has to be changed.
There are arguments that this is risky in terms of security (which I
suppose was the meaning of your "arbitrary classes" comment).
The exceptions would exist in either factory implementation
(with/without reflection), but the example has simplified them. BTW,
this example was shown in Bruce Eckel's book, Thinking in Java, if I
recall correctly.
Hemal Pandya - 14 Jul 2005 17:50 GMT
> [snip of java code]
> > I forgot... Why is this ugly reflective mess that drops exception
> > details and instantiates arbitrary classes "most maintainable"? Smells
> > kinda bad to me. I hope theres a good reason for this thing.
>
> Have you ever done a factory method before without reflection?
I have. Almost always, when the range of classes that can be
instantiated by the factory is known at compile time.
> It's a
> big, uglier "if" statement with hard-coded class names -
My code has a lot many other hard-coded class names. Most of my
variables are of hard-coded types actually. And I respectfully suspect
so are yours. <grin>
> If that approach is more
> maintainable, I don't see how, but I'm willing to listen to your
> explanation.
It maybe slightly less maintainable, because as you point out the
factory method has to be modified every time a candidate class is added
to the code base. But I am willing to tolerate the incremental effort
over creating that candidate class itself.
> Although a big if statement with "new" statements may be more readable,
Besides readability, it provides compile-time type checking and
declares in-code the range of classes that can be instantiated by the
factory.