randy.stafford | 7 Aug 21:20
Favicon

RE: Re: Factory Method Pattern via Inner Classes

Hi Aaron,

 

Nice to meet you.  It occurred to me too late, after my last reply in this thread, that I should have mentioned that I’ve appreciated your posts here recently; they have been insightful.

 

Turns out the pattern was named Constructor Method in the published Smalltalk Best Practice Patterns book (it was named Complete Creation Method in an earlier manuscript of the book, and in earlier works of Kent Beck).

 

The complexity involved in creating a valid (for some use) instance of a class seems to drive where and how to encode the creation logic, with the choices being simple constructors, Factory Methods, or Factory classes.  With the latter two choices, there is an additional decision as to where to “site” the Factory, to use Eric’s nice wording.  As an old Smalltalker, I’m accustomed to putting Factory Methods on the class of the created object (in the case of Complete Creation Methods), and on Aggregate Roots aggregating created objects e.g. OrderLineItem newLineItem(Product) on an Order class.  The original GoF Factory Method pattern description describes the general case of a Factory Method on a class which may be different than that of the created object.

 

When the complexity involved in creating a valid instance of a class is sufficient enough that a separate Factory class is warranted, it would make sense to me to use an inner class, for the reasons you mention, or at least some namespacing heuristic to closely associate the Factory class with that of the objects it creates.  The key points are to encapsulate (once and only once) what it takes to create a valid instance (without unduly opening access to private implementation details of the instantiated class), and to make it easy for programmers to find out how to create an instance of the class in question.  However in my experience it has been rare that the complexity of creating an instance is sufficient that a separate Factory class is warranted; I think that is an overused pattern, and Complete Creation Method suffices for me most of the time, especially for domain object classes.

 

With respect to the Single Responsibility Principle, I think there are other principles that are equally important, such as the Principle of High Cohesion.  There is high cohesion between the implementation of a class, and the requirements for properly instantiating a class, and therefore the logic for instantiating a class belongs with the implementation of the class.  Personally, I think SRP is overrated.  A class should implement as many responsibilities as makes sense for it to implement, where “makes sense” means the responsibilities in question are highly cohesive.

 

Kind Regards,

Randy

 

From: moffdub [mailto:moffdub <at> yahoo.com]
Sent: Thursday, August 07, 2008 6:51 AM
To: domaindrivendesign <at> yahoogroups.com
Subject: [domaindrivendesign] Re: Factory Method Pattern via Inner Classes

 

If it helps, my name is Aaron. :)

Thanks for the tip on the pattern. I have only found one good
resource on it. I will keep looking.

After sleeping on it, I agree that the inner class is a kludge, but I
think for different reasons. I reviewed what Jimmy Nilsson had to say
about this in his DDD book regarding Factory Methods:

"Are there any drawbacks? I think the main one is that I'm probably
violating the SRP when I have my creational code in the class itself.
Evans' book is a good reminder of that where he uses a metaphor of a
car engine. The car engine itself doesn't know how it is created;
that's not its responsibility."

This is the main reason why I shy away from Factory Methods, and my
inner class con was just that -- a con. Evans also says that one of
the main points of DDD factories is to be able to swap out the
creational code for a different implementation, and I clearly can't
do that with my suggestion.

I think the best trade-off is to consult the platform's way for
friend access or package access or equivalent, and apply that to
constructors. Nilsson to wit:

"To avoid the instantiation of orders via the constructor from other
classes in the Domain Model if the Factory code is an external class
is not possible, but you can make it a little less of a problem by
making the constructor internal, and hopefully because the Factory is
there, the Domain Model developers themselves understand that that's
the way of instantiating the class and not using the constructor of
the target class directly."

But still I wonder what workaround, aside from switching languages,
would be best if the platform doesn't come to the partial rescue.

__________________
The views expressed here are mine and do not reflect the official
opinion of my employer or the organization through which the Internet
was accessed

--- In domaindrivendesign <at> yahoogroups.com, randy.stafford <at> ... wrote:
>
> Hello Mr. Moffdub,
>
>
>
> I wish I knew your real name! You wrote:
>
>
>
> Doing Order.createOrder(-) works, but it seems contrary to the
spirit
> of separating the construction of the object from the object itself.
>
>
>
> That's the way we used to do it in Smalltalk (and I still do it
that way in Java). Kent Beck even wrote a pattern about it, called
Complete Creation Method in his Smalltalk Best Practice Patterns
book, renamed Complete Constructor in his more recent Implementation
Patterns book.
>
>
>
> I'm aware that my static inner class solution is essentially
> equivalent, save for clearer syntax for the caller.
>
>
>
> Beauty is in the eye of the beholder. I find Order.create
(customer, items) to be cleaner than Order.OrderFactory.createOrder
(customer, items). The latter seems to unnecessarily expose
implementation, and costs the development and maintenance of an
additional class which may not be entirely justified.
>
>
>
> Kind Regards,
>
> Randy Stafford
>
> http://c2.com/cgi/wiki?RandyStafford
>
>
>
> _____
>
> From: moffdub [mailto:moffdub <at> ...]
> Sent: Wednesday, August 06, 2008 4:07 PM
> To: domaindrivendesign <at> yahoogroups.com
> Subject: [domaindrivendesign] Re: Factory Method Pattern via Inner
Classes
>
>
>
> Thanks for the reply. Wouldn't delegating to a factory held in an
> instance variable cut you off from accessing private members?
>
> Assuming you are talking about a top-level class, the problem with
the
> factory using a constructor is I've made the constructor of Order
> private to force users of Order to use the factory.
>
> Doing Order.createOrder(-) works, but it seems contrary to the
spirit
> of separating the construction of the object from the object itself.
> I'm aware that my static inner class solution is essentially
> equivalent, save for clearer syntax for the caller.
>
> I think Order.OrderFactory.-createOrder(-), imperfect as it is,
makes it
> clear what is going on to someone cognizant of patterns.
> Order.createOrder(-) is a little less clear to me.
>
> --- In HYPERLINK "mailto:domaindrivendesign%
40yahoogroups.com"domaindrivendesign <at> ..., Michael Hunger <ddd <at> > wrote:
> >
> > I could also imagine using an factory method on the Order itself
> > -> Order.createOrder(-)
> > which then either:
> > * does the creation itself
> > * delegates to a static factory like your example
> > * delegates to an factory instance held in an instance variable
> (possibly setable by Dependency Injection)
> >
> > It depends on the complexity of the setup which approach you
choose
> to start with.
> >
> > I don't think this pollutes the Order to much because the creation
> of itself unproblematic in the sense of SRP.
> >
> > Another question is why you need access to internal fields in the
> factory and not just setting them in the constructor
> > (or on the other hand in a public factory method of the order
itself)?
> >
> > Michael
> >
> > --
> > Michael Hunger
> > Independent Consultant
> >
> > Web: HYPERLINK "http://www.jexp.de"http://www.jexp.-de
> > Email: michael.hunger <at>
> >
> > Enthusiastic Evangelist for Better Software Development
> >
> > Don't stop where you are: HYPERLINK "http://creating.passionate-
developers.org"http://creating.-passionate--developers.-org
> > We support Software Engineering Radio (www.se-radio.-net)
> >
>

__._,_.___

Your email settings: Individual Email|Traditional
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch to Fully Featured
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe

__,_._,___
Rickard Öberg | 8 Aug 03:18

Re: Re: Factory Method Pattern via Inner Classes

randy.stafford <at> oracle.com wrote:
> The complexity involved in creating a valid (for some use) instance of a 
> class seems to drive where and how to encode the creation logic, with 
> the choices being simple constructors, Factory Methods, or Factory 
> classes.  

In Qi4j we are using another pattern: the builder. This gives users an 
additional "phase" to creation, where the state is temporarily invalid 
while they provide state and necessary object references. It goes 
something like this:
ObjectBuilder<MyObject> builder = obf.newObjectBuilder(MyObject.class);
builder.use(otherObject, someObject); // Referenced objects; dependency 
injected
MyObject myobject = builder.newInstance();

But it is most useful for Entities, since the state-building phase can 
be quite drawn out, and possibly done in a UI:
EntityBuilder<Person> personBuilder = uow.newEntityBuilder(Person.class);

// The below could be done in a UI
// Get a fake proxy so we can set initial state
Person person = personBuilder.stateOfComposite();
person.name().set("Rickard");
person.email().set("rickardoberg <at> gmail.com");

Person rickard = personBuilder.newInstance();

Validation and constraints are only checked at the time of 
newInstance(), and any properties that have not been set are filled in 
with the defined defaults. Constraints such as "name must not be empty" 
are hence allowed to be invalid during builder time, but not at 
newInstance() time.

In the above, Person might be defined like so:
interface Person
{
   @NotEmpty Property<String> name();
   @Email Property<String> email();
}

> With the latter two choices, there is an additional decision 
> as to where to “site” the Factory, to use Eric’s nice wording.  As an 
> old Smalltalker, I’m accustomed to putting Factory Methods on the class 
> of the created object (in the case of Complete Creation Methods), and on 
> Aggregate Roots aggregating created objects e.g. OrderLineItem 
> newLineItem(Product) on an Order class.  The original GoF Factory Method 
> pattern description describes the general case of a Factory Method on a 
> class which may be different than that of the created object.

In the Qi4j case, the factory(/builder) is provided by the framework, in 
a generic style. This may in turn be wrapped in custom factory methods 
if more complex logic is necessary.

> With respect to the Single Responsibility Principle, I think there are 
> other principles that are equally important, such as the Principle of 
> High Cohesion.  There is high cohesion between the implementation of a 
> class, and the requirements for properly instantiating a class, and 
> therefore the logic for instantiating a class belongs with the 
> implementation of the class.  Personally, I think SRP is overrated.  A 
> class should implement as many responsibilities as makes sense for it to 
> implement, where “makes sense” means the responsibilities in question 
> are highly cohesive.

And, speaking from a Qi4j perspective, I of course totally agree, with 
the slight difference "An *object* should implement as many 
responsibilities as makes sense for it", and then mixins, constraints, 
concerns etc. (implemented by individual classes) are used to fulfill 
those responsibilities. This gives you the best of both worlds: a 
capable non-anemic object and classes with truly only single 
responsibilities.

/Rickard

------------------------------------

moffdub | 8 Aug 04:07
Favicon

Re: Factory Method Pattern via Inner Classes

Hi Randy,

Well thanks very much. I've spent a lot of time, since joining this
group, combing through archives, and I appreciate the insight of
others as well. Very informative.

But be careful on giving me too much praise too quickly. Having just
joined this group after mulling over DDD since I started practicing it
(a mere year), I have a lot of pent-up stuff to say on DDD that only
recently has been typed out on my blog. More gray areas occur to me
each time I try to sharpen my skills. 

I really don't know why I didn't join this group sooner. I had known
about its existence for quite a while but never joined. I have no idea
why.

Back on point. As far as your commitment to the Constructor Method
Pattern, how would you go about enabling different implementations to
be interchanged easily? Would a separate factory class not afford you
higher flexibility?

In my case, the creation of the object was dependent on, aside from
simple instance variable initialization, some information in a couple
of XML files. I thought this was as clear an indicator as it could get
that I needed a factory to call some sort of XML service. 

I have a lot of reverence for ideas and suggestions that have their
roots in Smalltalk. It seems to me like the original OO language. I've
always thought that a DDD factory subsumes GoF factory patterns. Eric
stated clearly that whenever the construction of the object is
complicated enough, it should go in a factory. Whether that involves
an interface or inheritance hierarchy doesn't seem to matter.

And in a lot of cases, there aren't a plethora of hierarchies to
navigate. Jimmy Nilsson's book is a solid companion to Eric's because
it fills in the gaps with plenty of examples, and this is one covered
in the text.

Looking at it the other way, I could also argue that the GoF patterns
subsume the DDD factory pattern. However, I've never been one to
sprinkle interfaces with each and every class I write; only if I think
implementation will actually change depending on the situation.

It occurs to me that the friend modifier in C++ would let us both hide
implementation details, constructor included, of the domain object,
*and* unambiguously communicate to other developers to use the
factory. After all, if the constructors are private, the compiler will
slap them down. C++ got something right after all. 

I concur with you 100% that factory patterns are over-used. I have
been guilty of this sin in the past.

You have an interesting take on SRP. I can see your cohesion argument,
because for an object to be properly constructed, whomever is doing
the constructing should have access to the object's internals. This is
why C++'s friend keyword is so convenient here. Cohesion also helps
out when it comes to ensuring that invariants are satisfied upon
creation. 

But who's to say whether this is cohesive? One person might claim it
is, while another will say that expressing the concept of an Order
from "real life" has nothing to do with instantiating this class and
that class and this other ArrayList, let alone choosing the right
derived class, and ensuring that some invariants are satisfied. In
real life, the Order is what it is, and it doesn't "validate" itself.

I'm willing to grant you that when responsibilities get too
fine-grained, that you can get into trouble. I think SRP applies to
concerns in terms of scoping. And what I mean by that is that concerns
like creation of objects, persistence of objects, modeling of objects,
and display of objects are responsibilities that should be segregated.
And within the domain, an Order class should be responsible for all
data and logic associated with a single Order; or, if you prefer, all
the responsibilities (plural) that go with a single Order: data,
logic, managing state transitions, etc.

This same scoping description applies outside of the domain as well.
An XML parsing service is responsible for the single responsibility of
chopping XML and returning nodes, or you can say it is responsible for
all responsibilities concerning chopping XML: traversal algorithm,
instantiating nodes, etc.

That said, of course it all comes down to how you hierarchal-ize (not
a real word I'm sure) the responsibilities. It all depends. Cohesion
is as ill-defined as most design concepts. We get no breaks in this
field. We get to decide everything. 

--- In domaindrivendesign <at> yahoogroups.com, randy.stafford@... wrote:
>
> Hi Aaron,
> 
>  
> 
> Nice to meet you.  It occurred to me too late, after my last reply
in this thread, that I should have mentioned that I've appreciated
your posts here recently; they have been insightful.
> 
>  
> 
> Turns out the pattern was named Constructor Method in the published
Smalltalk Best Practice Patterns book (it was named Complete Creation
Method in an earlier manuscript of the book, and in earlier works of
Kent Beck).
> 
>  
> 
> The complexity involved in creating a valid (for some use) instance
of a class seems to drive where and how to encode the creation logic,
with the choices being simple constructors, Factory Methods, or
Factory classes.  With the latter two choices, there is an additional
decision as to where to "site" the Factory, to use Eric's nice
wording.  As an old Smalltalker, I'm accustomed to putting Factory
Methods on the class of the created object (in the case of Complete
Creation Methods), and on Aggregate Roots aggregating created objects
e.g. OrderLineItem newLineItem(Product) on an Order class.  The
original GoF Factory Method pattern description describes the general
case of a Factory Method on a class which may be different than that
of the created object.
> 
>  
> 
> When the complexity involved in creating a valid instance of a class
is sufficient enough that a separate Factory class is warranted, it
would make sense to me to use an inner class, for the reasons you
mention, or at least some namespacing heuristic to closely associate
the Factory class with that of the objects it creates.  The key points
are to encapsulate (once and only once) what it takes to create a
valid instance (without unduly opening access to private
implementation details of the instantiated class), and to make it easy
for programmers to find out how to create an instance of the class in
question.  However in my experience it has been rare that the
complexity of creating an instance is sufficient that a separate
Factory class is warranted; I think that is an overused pattern, and
Complete Creation Method suffices for me most of the time, especially
for domain object classes.
> 
>  
> 
> With respect to the Single Responsibility Principle, I think there
are other principles that are equally important, such as the Principle
of High Cohesion.  There is high cohesion between the implementation
of a class, and the requirements for properly instantiating a class,
and therefore the logic for instantiating a class belongs with the
implementation of the class.  Personally, I think SRP is overrated.  A
class should implement as many responsibilities as makes sense for it
to implement, where "makes sense" means the responsibilities in
question are highly cohesive.
> 
>  
> 
> Kind Regards,
> 
> Randy
> 
>  
> 

------------------------------------


Gmane