4

I have a real-world problem which I'll try to abstract into an illustrative example.

So imagine I have data objects in a tree, where parent objects can access children, and children can access parents:

// Interfaces
interface IParent<TChild> { List<TChild> Children; }
interface IChild<TParent> { TParent Parent; }

// Classes
class Top : IParent<Middle> {}
class Middle : IParent<Bottom>, IChild<Top> {}
class Bottom : IChild<Middle> {}

// Usage
var top = new Top();
var middles = top.Children; // List<Middle>
foreach (var middle in middles) {
    var bottoms = middle.Children; // List<Bottom>
    foreach (var bottom in bottoms) {
        var middle = bottom.Parent; // Access the parent
        var top = middle.Parent; // Access the grandparent
    }
}

All three data objects have properties that are persisted in two data stores (e.g. a database and a web service), and they need to reflect and synchronise with the stores. Some objects only request from the web service, some only write to it.

Data Mapper

My favourite pattern for data access is Data Mapper, because it completely separates the data objects themselves from the communication with the data store:

class TopMapper {
    public Top FetchById(int id) {
        var top = new Top(DataStore.TopDataById(id));
        top.Children = MiddleMapper.FetchForTop(Top);
        return Top;
    }
}

class MiddleMapper {
    public Middle FetchById(int id) {
         var middle = new Middle(DataStore.MiddleDataById(id));
         middle.Parent = TopMapper.FetchForMiddle(middle);
         middle.Children = BottomMapper.FetchForMiddle(bottom);
         return middle;
    }
}

This way I can have one mapper per data store, and build the object from the mapper I want, and then save it back using the mapper I want.

There is a circular reference here, but I guess that's not a problem because most languages can just store memory references to the objects, so there won't actually be infinite data.

The problem with this is that every time I want to construct a new Top, Middle or Bottom, it needs to build the entire object tree within that object's Parent or Children property, with all the data store requests and memory usage that that entails. And in real life my tree is much bigger than the one represented here, so that's a problem.

Requests in the object

In this the objects request their Parents and Children themselves:

class Middle {
    private List<Bottom> _children = null; // cache
    public List<Bottom> Children {
        get {
            _children = _children ?? BottomMapper.FetchForMiddle(this);
            return _children;
        }
        set {
            BottomMapper.UpdateForMiddle(this, value);
            _children = value;
        }
    }
}

I think this is an example of the repository pattern. Is that correct?

This solution seems neat - the data only gets requested from the data store when you need it, and thereafter it's stored in the object if you want to request it again, avoiding a further request.

However, I have two different data sources. There's a database, but there's also a web service, and I need to be able to create an object from the web service and save it back to the database and then request it again from the database and update the web service.

This also makes me uneasy because the data objects themselves are no longer ignorant of the data source. We've introduced a new dependency, not to mention a circular dependency, making it harder to test. And the objects now mask their communication with the database.

Other solutions

Are there any other solutions which could take care of the multiple stores problem but also mean that I don't need to build / request all the data every time?

7
  • What language are you using? C#?
    – occulus
    Commented Dec 3, 2012 at 17:33
  • 3
    Btw I always find it strange when I hear someone saying "favourite pattern". It's like saying "I have a favourite hammer" -- different hammers are useful for different jobs. Forget about how cool the hammer is and recognise it as appropriate for certain jobs, and other hammers appropriate for different jobs, etc.
    – occulus
    Commented Dec 3, 2012 at 17:37
  • 2
    @occulus but people do have favourite hammers, because with the proliferation of hammers out there, they can be similar but vary slightly. The same is true of design patterns. As there is no absolute authoritative source for all "approved" design patterns (not everything is in Gang of Four), there are loads of slightly different but very similar ones created by different communities. When I say my favourite I mean I think it's the neatest but I recognise other people have other opinions. It would be the same with a hammer. However I'm willing to accept if in this case my choice is just wrong Commented Dec 4, 2012 at 9:20
  • @occulus I'm using C# in this case, but patterns should hopefully be language independent no? Commented Dec 4, 2012 at 9:21
  • Don't get me wrong, I'm not saying any of the patterns you've mentioned are wrong per se, it was more just a case of hearing the phrase 'favourite pattern' really. But I see what you're getting at.
    – occulus
    Commented Dec 4, 2012 at 13:23

2 Answers 2

3

The undesirable part of your approach comes from having the data objects themselves unfreezing (loading, deserialising) themselves.

This is not a simple problem!

Ideally you want your data objects being quite simple, and some external agent being responsible for deserialising and serialising them using data that lives on disk, or on the network, etc.

One approach to this might use reflection and object introspection and fancy things like that.

Another approach might use to use "generic objects". A generic object can store an arbitrary amount of properties (i.e. fields/variables). Each field can be one of a few set types: int, string, byte array, reference to another generic object (that one is important), etc. So you can then model your data objects as generic objects.

The advantage of using "generic objects" is that you can then have a mechanism external (or super) to the generic object class through which its properties are accessed. This mechanism recognises when a field hasn't yet been loaded, and can fetch it from the appropriate source. It an also handle cache writing, e.g. fetching data from remote source, writing to to local cache.

The above is a very general sounding description, but it's not a trivial thing to implement so it might be hard to get any more specific without getting very verbose.

See also this SO question: https://stackoverflow.com/questions/9200545/recommended-pattern-for-lazy-loading-portions-of-object-graph-from-cache

Also note that Core Data in iOS is an object grapher which handles lazy loading (faulting) -- your problem area is very similar to what Core Data addresses.

Core Data is an object graph and persistence framework provided by Apple [...] It allows data organised by the relational entity–attribute model to be serialised into XML, binary, or SQLite stores. The data can be manipulated using higher level objects representing entities and their relationships. Core Data manages the serialised version, providing object lifecycle and object graph management, including persistence.

0

I ended up sticking with the DataMapper pattern, but then changing my application:

For a long time I was using a builder to build up the complex object tree. But over time, I discovered that the inflexibility of this system made the code un-maintainable.

I now think that the problem of constructing objects where parent objects can access children and children can access parents is difficult for a good reason: because it's trying to create objects that are too tightly coupled to each other. Because of the tight coupling, it is impossible to create any objects without building up the entire tree.

What I ended up doing was restructuring the rest of my application to remove any hard dependencies, and instead including FetchForChild and FetchForParent methods on my DataMapper object, loosening the coupling.

This now works very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.