Re: Synchronization of the constructor
Qu0ll wrote:
Lew wrote:
[snip]
Point being that there are particular use cases when it's OK to use a
constructor if the advantages of a factory method are not particularly=
compelling, or if the hoops to implement and use a factory method are
too epicyclic. But Patricia's advice and insights are very sound (as th=
ey
always are from her); factory methods bring great advantages for a lot o=
f
scenarios. I certainly plan to increase my appreciation for them
because of her post.
In general is it better to have static factory methods on the class that =
is
to be instantiated or to have a separate factory class?
That is a very good question.
I don't think there is a general rule here. You have to do what is smart f=
or the given situation. Either way, make sure the factory method is well w=
ritten.
If the construction is tightly bound to the class under construction, that =
would argue for the static method belonging to the class to be built. OTOH=
, if the factory is one of a class of factories, e.g., for collections, the=
n it might make more sense to push it out into a helper class. Do what mak=
es for the cleanest design that is easiest to maintain over the long term f=
or the scenario. One goal is to make it easy to figure out where the facto=
ry is when you need instances. Another is to have compiler-enforced type s=
afety.
Also, there may be cases where the factory method should be an instance met=
hod of a separate class, e.g., if you want to load a configuration to guide=
the construction and have different instances work from different configur=
ations.
Do what makes sense.
--
Lew