randy.stafford | 7 Aug 04:34
Favicon

RE: Re: Factory Method Pattern via Inner Classes

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> yahoo.com]
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 domaindrivendesign <at> yahoogroups.com, 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: http://www.jexp.de
> Email: michael.hunger <at> ...
>
> Enthusiastic Evangelist for Better Software Development
>
> Don't stop where you are: 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

__,_._,___
moffdub | 7 Aug 14:50
Favicon

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@... 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@...] 
> 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@..., Michael Hunger <ddd@> 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@
> > 
> > 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)
> >
>

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

moffdub | 6 Sep 21:50
Favicon

Re: Factory Method Pattern via Inner Classes

I thought I'd revisit this thread and share one of my recent flashes
of insanity on this topic.

Basically, I want 

* no unnecessary getters and setters in the Order domain object
* no way for the wrong classes to use any sort of getters or setters
* all construction of Orders to go through the OrderFactory
* to be able to swap versions of OrderFactory 
* not implement the factory within the Order domain object itself
* repositories to have a way of getting the data they need to save Orders

Here is what I came up with: still use an inner class, since that
inner class has access to all the privates of Order, but instead of
putting the factory logic there, just provide wrappers for getters and
setters. Also make the class abstract, and the wrappers non-public.

    public class Order
    {
        private uint number;
        private String description;

        private Order()
        {
        }

        public void bizMethod1()
        {
            // stuff here
        }

        public void bizMethod2()
        {
            // stuff here
        }

        public abstract class OrderAccessor
        {
            private Order o;

            protected OrderAccessor()
            {
                this.o = new Order();
            }

            protected OrderAccessor(Order o)
            {
                this.o = o;
            }

            protected void setNumber(uint number)
            {
                this.o.number = number;
            }

            protected void setDesc(String d)
            {
                this.o.description = d;
            }

            protected uint getNumber()
            {
                return this.o.number;
            }

            protected String getDesc()
            {
                return this.o.description;
            }

            protected Order getOrder()
            {
                return this.o;
            }
        }
    }

OrderAccessor can't be instantiated, so other classes can't just use
it willy-nilly. Even if they could, all of the methods are protected
anyway.

Now have the OrderFactory extend this class. OrderFactory can be in
the same assembly/jar or a different one, making it easy to swap
implementations.

    public class OrderFactory : Order.OrderAccessor
    {
        public Order createNew()
        {
            setDesc("");
            setNumber(1);
            return getOrder();
        }
    }

You can get more sophisticated by having OrderFactory implement an
interface that is programmed against, of course.

Now use it:

Order anOrder = (new OrderFactory()).createNew();

Same sort of reasoning goes for the repository:

    public class OrderRepository
    {
        public void store(Order anOrder)
        {
            OrderDataGatherer odg = new OrderDataGatherer(anOrder);

            String qryStr = "INSERT INTO Orders " +
                "(Num, Desc) VALUES (" + odg.getNumber() + ", " +
                odg.getDesc() + ")";

        }
    }

    internal class OrderDataGatherer : Order.OrderAccessor
    {
        public OrderDataGatherer(Order o): base(o)
        {

        }

        public new uint getNumber()
        {
            return base.getNumber();
        }

        public new String getDesc()
        {
            return base.getDesc();
        }
    }

But it still isn't perfect, because OrderAccessor is public, meaning
any damn class at all can inherit from it and use the inherited
getters and setters. I give up!

--- In domaindrivendesign <at> yahoogroups.com, "moffdub" <moffdub@...> wrote:
>
> 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.
> 

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

Michael Hunger | 7 Sep 06:27

Re: Re: Factory Method Pattern via Inner Classes

Perhaps an order being able to construct itself from a template would help here? Then you could pass in any
order 
template you want to provide (perhaps even add validation in the copying process and/or the order template).

This is the "Mutable Companion to Immutable Object"-Pattern which reduces some of the overhead of heavily
modifying 
immutable objects. In the JDK there is an example for this with MutableBigInteger + BigInteger.

Michael

moffdub schrieb:
> I thought I'd revisit this thread and share one of my recent flashes
> of insanity on this topic.
> 
> Basically, I want 
> 
> * no unnecessary getters and setters in the Order domain object
> * no way for the wrong classes to use any sort of getters or setters
> * all construction of Orders to go through the OrderFactory
> * to be able to swap versions of OrderFactory 
> * not implement the factory within the Order domain object itself
> * repositories to have a way of getting the data they need to save Orders
> 
> Here is what I came up with: still use an inner class, since that
> inner class has access to all the privates of Order, but instead of
> putting the factory logic there, just provide wrappers for getters and
> setters. Also make the class abstract, and the wrappers non-public.
> 
>     public class Order
>     {
>         private uint number;
>         private String description;
> 
>         private Order()
>         {
>         }
> 
>         public void bizMethod1()
>         {
>             // stuff here
>         }
> 
>         public void bizMethod2()
>         {
>             // stuff here
>         }
> 
>         public abstract class OrderAccessor
>         {
>             private Order o;
> 
>             protected OrderAccessor()
>             {
>                 this.o = new Order();
>             }
> 
>             protected OrderAccessor(Order o)
>             {
>                 this.o = o;
>             }
> 
>             protected void setNumber(uint number)
>             {
>                 this.o.number = number;
>             }
> 
>             protected void setDesc(String d)
>             {
>                 this.o.description = d;
>             }
> 
>             protected uint getNumber()
>             {
>                 return this.o.number;
>             }
> 
>             protected String getDesc()
>             {
>                 return this.o.description;
>             }
> 
>             protected Order getOrder()
>             {
>                 return this.o;
>             }
>         }
>     }
> 
> OrderAccessor can't be instantiated, so other classes can't just use
> it willy-nilly. Even if they could, all of the methods are protected
> anyway.
> 
> Now have the OrderFactory extend this class. OrderFactory can be in
> the same assembly/jar or a different one, making it easy to swap
> implementations.
> 
>     public class OrderFactory : Order.OrderAccessor
>     {
>         public Order createNew()
>         {
>             setDesc("");
>             setNumber(1);
>             return getOrder();
>         }
>     }
> 
> You can get more sophisticated by having OrderFactory implement an
> interface that is programmed against, of course.
> 
> Now use it:
> 
> Order anOrder = (new OrderFactory()).createNew();
> 
> Same sort of reasoning goes for the repository:
> 
>     public class OrderRepository
>     {
>         public void store(Order anOrder)
>         {
>             OrderDataGatherer odg = new OrderDataGatherer(anOrder);
> 
>             String qryStr = "INSERT INTO Orders " +
>                 "(Num, Desc) VALUES (" + odg.getNumber() + ", " +
>                 odg.getDesc() + ")";
>             
>         }
>     }
> 
>     internal class OrderDataGatherer : Order.OrderAccessor
>     {
>         public OrderDataGatherer(Order o): base(o)
>         {
> 
>         }
> 
>         public new uint getNumber()
>         {
>             return base.getNumber();
>         }
> 
>         public new String getDesc()
>         {
>             return base.getDesc();
>         }
>     }
> 
> But it still isn't perfect, because OrderAccessor is public, meaning
> any damn class at all can inherit from it and use the inherited
> getters and setters. I give up!
> 
> --- In domaindrivendesign <at> yahoogroups.com, "moffdub" <moffdub@...> wrote:
>> 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.
>>
> 
> 

--

-- 
Michael Hunger
Independent Consultant

Web: http://www.jexp.de
Email: michael.hunger <at> jexp.de

Enthusiastic Evangelist for Better Software Development

Don't stop where you are: http://creating.passionate-developers.org
We support Software Engineering Radio (www.se-radio.net)

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

moffdub | 7 Sep 17:30
Favicon

Re: Factory Method Pattern via Inner Classes

That would certainly work, but I'm trying to keep the factory itself
separated from the domain object. This way, you adhere to SRP and the
implementations can be easily changed w/o touching the domain object.

Anyway, I slept on it, and the problem really boils down to simulating
friend classes in a language that lacks friend classes.

The solution I posted yesterday is garbage because it won't mesh if
you have an abstract factory pattern to use because of the inheritance.

I played with it again this morning, and here is what I found that
just might work:

1. keep the inner class (the "accessor" that has getters and setters),
but make it concrete and private, and have it implement an interface.

2. let the domain object "declare" its friends by requiring all
instantiation of those classes through the domain object. So, Order
has a method repository() to return a new OrderRepository, and also a
factory() to return a new OrderFactory.

3. each of those friends has the inner class's interface injected by
the domain object

User code looks like this:

            bob = Customer.factory().createNew().
                           withName("Bob").
                           withID(15);

            Customer jane = Customer.repository().findByID(18);

            Customer.repository().save(jane);

and it hits everything on my checklist:

* no unnecessary getters and setters in the Order domain object
covered - the getters and setters are in the private inner accessor class

* no way for the wrong classes to use any sort of getters or setters
covered - the domain object is the only class allowed to instantiate
the accessor class

* all construction of Orders to go through the OrderFactory
covered - the domain object's factory is private, and it is called
within the domain object itself when the private inner accessor class
is being instantiated

* to be able to swap versions of OrderFactory
covered - the factory is a separate class and doesn't have to inherit
from anyone

* not implement the factory within the Order domain object itself
covered - see above

* repositories to have a way of getting the data they need to save Orders
covered - they can inject the Order they want to save into the
accessor interface that Order gives it upon construction

I almost have it working with an abstract factory, except my situation
is with a concrete base class AND subclasses, instead of the typical
abstract base class.

Since I have obsessed with this topic far more than a normal person
should, if anyone wants to see the code, just holler.

--- In domaindrivendesign <at> yahoogroups.com, Michael Hunger <ddd@...> wrote:
>
> Perhaps an order being able to construct itself from a template
would help here? Then you could pass in any order 
> template you want to provide (perhaps even add validation in the
copying process and/or the order template).
> 
> This is the "Mutable Companion to Immutable Object"-Pattern which
reduces some of the overhead of heavily modifying 
> immutable objects. In the JDK there is an example for this with
MutableBigInteger + BigInteger.
> 
> Michael
> 

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

Sean Chambers | 7 Sep 18:08
Favicon

Re: Factory Method Pattern via Inner Classes

The only problem with this:

>             bob = Customer.factory().createNew().
>                            withName("Bob").
>                            withID(15);
> 
>             Customer jane = Customer.repository().findByID(18);
> 
>             Customer.repository().save(jane);

is that it violates the law of demeter. not too big of a deal, but a 
violation nonetheless.

Personally, I would not choose this approach as it begins to mix 
together concepts of persistence, construction along with a domain 
entity. In other words, is it a domain concept/language that a 
Customer has a "Factory"? This sounds like its an application layer 
concern and not a core concept of your domain, therefore it feels 
misplaced in this example.

Reading your previous posts, couldn't you just use reflection to 
construct the object if you are concerned with public getters/setters? 

I may have missed something in the string of posts as to the reason 
you have chosen to accomplish it in this manner.

Sean

--- In domaindrivendesign <at> yahoogroups.com, "moffdub" <moffdub@...> 
wrote:
>
> That would certainly work, but I'm trying to keep the factory itself
> separated from the domain object. This way, you adhere to SRP and 
the
> implementations can be easily changed w/o touching the domain 
object.
> 
> Anyway, I slept on it, and the problem really boils down to 
simulating
> friend classes in a language that lacks friend classes.
> 
> The solution I posted yesterday is garbage because it won't mesh if
> you have an abstract factory pattern to use because of the 
inheritance.
> 
> I played with it again this morning, and here is what I found that
> just might work:
> 
> 1. keep the inner class (the "accessor" that has getters and 
setters),
> but make it concrete and private, and have it implement an 
interface.
> 
> 2. let the domain object "declare" its friends by requiring all
> instantiation of those classes through the domain object. So, Order
> has a method repository() to return a new OrderRepository, and also 
a
> factory() to return a new OrderFactory.
> 
> 3. each of those friends has the inner class's interface injected by
> the domain object
> 
> User code looks like this:
> 
>             bob = Customer.factory().createNew().
>                            withName("Bob").
>                            withID(15);
> 
>             Customer jane = Customer.repository().findByID(18);
> 
>             Customer.repository().save(jane);
> 
> and it hits everything on my checklist:
> 
> * no unnecessary getters and setters in the Order domain object
> covered - the getters and setters are in the private inner accessor 
class
> 
> * no way for the wrong classes to use any sort of getters or setters
> covered - the domain object is the only class allowed to instantiate
> the accessor class
> 
> * all construction of Orders to go through the OrderFactory
> covered - the domain object's factory is private, and it is called
> within the domain object itself when the private inner accessor 
class
> is being instantiated
> 
> * to be able to swap versions of OrderFactory
> covered - the factory is a separate class and doesn't have to 
inherit
> from anyone
> 
> * not implement the factory within the Order domain object itself
> covered - see above
> 
> * repositories to have a way of getting the data they need to save 
Orders
> covered - they can inject the Order they want to save into the
> accessor interface that Order gives it upon construction
> 
> I almost have it working with an abstract factory, except my 
situation
> is with a concrete base class AND subclasses, instead of the typical
> abstract base class.
> 
> Since I have obsessed with this topic far more than a normal person
> should, if anyone wants to see the code, just holler.
> 
> --- In domaindrivendesign <at> yahoogroups.com, Michael Hunger <ddd@> 
wrote:
> >
> > Perhaps an order being able to construct itself from a template
> would help here? Then you could pass in any order 
> > template you want to provide (perhaps even add validation in the
> copying process and/or the order template).
> > 
> > This is the "Mutable Companion to Immutable Object"-Pattern which
> reduces some of the overhead of heavily modifying 
> > immutable objects. In the JDK there is an example for this with
> MutableBigInteger + BigInteger.
> > 
> > Michael
> >
>

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

moffdub | 7 Sep 19:29
Favicon

Re: Factory Method Pattern via Inner Classes

I agree with you that it isn't pretty to have factory() and
repository() methods in Customer. However, if you don't give Customer
the ability to control who gets to work with instantiations of its
accessor class, then you risk other classes, like other domain
classes, who shouldn't be able to call getXXXX and setXXXX to get a
hold of them and by-pass your domain logic.

On the bright side, the actual implementation of the factory and
repository are in separate classes, or could even be in separate
assemblies.

Of course, all of this would be nicely solved if you have friend
classes, like C++. I got this idea of asking Customer for the factory
or repository from a recent post about Fluent Builders. The only part
I don't like about Fluent Builders is that they are implemented as
inner classes right in the domain object.

Re: factories -- actually, the party line is that factories are domain
objects, according to Evans.

And yes, I could use reflection, but just like package-level /
internal access modifiers, I'm looking for something that isn't as
platform-dependent as reflection. Plus, package-level / internal
access modifiers are a solution that won't scale. I don't want a DLL
for each and every domain object.

Also, in those very rare cases where performance matters that much,
reflection might be frowned upon.

--- In domaindrivendesign <at> yahoogroups.com, "Sean Chambers"
<dkode8880@...> wrote:
>
> The only problem with this:
> 
> >             bob = Customer.factory().createNew().
> >                            withName("Bob").
> >                            withID(15);
> > 
> >             Customer jane = Customer.repository().findByID(18);
> > 
> >             Customer.repository().save(jane);
> 
> is that it violates the law of demeter. not too big of a deal, but a 
> violation nonetheless.
> 
> Personally, I would not choose this approach as it begins to mix 
> together concepts of persistence, construction along with a domain 
> entity. In other words, is it a domain concept/language that a 
> Customer has a "Factory"? This sounds like its an application layer 
> concern and not a core concept of your domain, therefore it feels 
> misplaced in this example.
> 
> Reading your previous posts, couldn't you just use reflection to 
> construct the object if you are concerned with public getters/setters? 
> 
> I may have missed something in the string of posts as to the reason 
> you have chosen to accomplish it in this manner.
> 
> Sean
> 

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


Gmane