views:

258

answers:

2

Over the years, I think I have seen and tried every conceivable way of generating stub data structures (fake data) for complex object graphs. It always gets hairy in java.

   *    *    *    *
A---B----C----D----E

(Pardon cheap UML)

The key issue is that there are certain relationships between the values, so a certain instance of C may imply given values for E.

Any attempt I have seen at applying a single pattern or group of pattens to solve this problem in java ultimately end up being messy.

I am considering if groovy or any of the dynamic vm languages can do a better job. It should be possible to do things significantly simpler with closures.

Anyone have any references/examples of this problem solved nicely with (preferably) groovy or scala ?

Edit: I did not know "Object Mother" was the name of the pattern, but it's the one I'm having troubles with: When the object structure to be generated by the Object Mother is sufficiently complex, you'll always end up with a fairly complex internal structure inside the Object Mother itself (or by composing multiple Object Mothers). Given a sufficiently large target structure (Say 30 classes), finding structured ways to implement the object mother(s) is really hard. Now that I know the name of the pattern i can google it better though ;)

+2  A: 

You might find the Object Mother pattern to be useful. I've used this on my current Groovy/Grails project to help me create example data.

It's not groovy specific, but a dynamic language can often make it easier to create something like this using duck typing and closures.

Ted Naleid
Thanks for the pattern name. Now google can help me
krosenvold
+1  A: 

I typically create object mothers using the builder pattern.

public class ItineraryObjectMother
{
    Status status;
    private long departureTime;

    public ItineraryObjectMother()
    {
        status = new Status("BLAH");
        departureTime = 123456L;
    }
    public Itinerary build()
    {
        Itinerary itinerary = new Itinerary(status);
        itinerary.setDepartureTime(departureTime);
        return itinerary;
    }
    public ItineraryObjectMother status(Status status)
    {
        this.status = status;
        return this;
    }
    public ItineraryObjectMother departs(long departureTime)
    {
        this.departureTime = departureTime;
        return this;
    }

}

Then it can be used like this:

Itinerary i1 = new ItineraryObjectMother().departs(1234L).status(someStatus).build();
Itinerary i2 = new ItineraryObjectMother().departs(1234L).build();

As Ted said, this can be improved/simplified with a dynamic language.

Javid Jamae