Re: News for Java?
Lew wrote:
Factories can set immutable public state for their clients. They control
the constructors, hiding them from the outside, so their use is
compatible with setting state in constructors of the hidden
implementation classes.
public interface Fooster
{
public Condition getInitialCondition();
public void foo();
}
public class FoosterFactory
{
public static Fooster produce( Condition condition )
{
return new FoosterImpl( condition );
}
}
public class Client
{
public void doSomething()
{
Condition condition = createInitialCondition();
Fooster fooster = FoosterFactory.produce( condition );
fooster.foo();
}
}
Arne Vajh??j wrote:
That is possible.
But not always practical.
A truism for all useful idioms. It's not always practical.
Usually you figure that out early as you consider each approach.
Personally I'm not sold on the idea that factories are usually better than
constructors, let alone always. Certainly they're sometimes better.
It becomes problematic with variable number of properties.
And it put requirements on FoosterImpl beyond just
implementing Fooster.
You are right. One has to be aware of these risks and code defensively.
OTOH, the contract for Fooster only allows getters, so one could say that an
implementation with a setter goes beyond what it should implement. The
interface only exposes observable state, not mutable state, so whether the
implementation is immutable is opaque to the client. It is in many cases most
reasonable to implement such a read-only type with an immutable implementation.
Having too many properties in a factory call is an antipattern, for various
values of "too many". It's easier if the parameters have different types, but
it's still dicey after a few. One could collect parameters into
initialization types, such as the 'Condition' type implied in my example. Its
instances live briefly and locally, so the type can be pretty unsafe -
mutable, not thread safe, overridable (well, maybe not overridable) - even if
the factory doesn't defensively copy its initialization parameters.
The type would require perhaps a little documentation - the Javadocs can warn
against violations of non-enforceable assumptions, much as the hashed
collections APIs warn against base types with inconsistent 'hashCode()' and
'equals()'. It ain't always pure, but it'll git 'er done.
This goes back to the point of the subthread - consider carefully when
designing public state. There are pros and cons to each specific approach, as
in the example here. There might be more than one viable approach. Whatever
the individual decisions, the practice of intelligent consideration will
engender stabler systems.
--
Lew
Ceci n'est pas une pipe.