views:

105

answers:

1

In Martin Fowler's Patterns for Enterprise Application Architectures book (page 229 in German, Lazy Load) he gives an example with this code:

public List getProducts() {
    if (products == null) products = Product.findForSupplier(getID());
    return products;
}

like you can see, the finder method seems to be part of the domain class Product. This confuses me a little bit, since I thought everything related to retrieving objects from somewhere (often a database, but business logic shouldn't care) should be part of the Data Mapper (PersonDataMapper) class. Probably I just missed something?

+1  A: 

The example you gave is the easy method for Lazy Loading. Person is unlikely using a DataMapper. As Fowler states in the english book (201):

Using lazy initialization is simple, but it does tend to force a dependency between the object and the database. For that reason it works best for ActiveRecord, Table Data Gateway and Row Data Gateway. If you are using Data Mapper, you'll need an additional layer of indirection, which you can obtain by using a virtual proxy [GOF].

As for everything [...] should be in the DataMapper, well.. yes, but also no. What you should keep in mind when working with design patterns is when to use them and when not. DataMapper is not the Holy Grail. It's not the only way to do it. When your app is just a small and simple CRUD app living on the web, then the added complexity of a Data Mapper and/or using a Domain Model is likely not worth the effort.

In addition, design patterns are generic good practise approaches to common software problems. While you may be able to apply them to your concrete problems as they are given in a book, there is no reason to follow them religiously. If something in a pattern would overly complicate your problem solving, then keep it simple. Derive. Adjust. Solve the problem.

Gordon
I agree with you, maybe a DataMapper pattern is really over-development in my case. But I try to develop now something for my little site, that will also be useful as soon as I have an idea for something really big/complex. Going to just add finders to the DataMapper as it sounds reasonable to me ;)
openfrog
See, that's the point. Use it, when you need it. If you ain't gonna need it, leave it out. I know it is tempting not to, but it does not add any value to your app to have it now.
Gordon