views:

189

answers:

3

Hi,

I am in the process of refactoring our BI layers to make our code more "loosely coupled" and I was interested to hear what you guys thought might be interesting improvements to make?

At present, our API is something like the following:-

// Fetch a collection of objects
ProductCollection prods = Product.GetProducts();

// Load an individual object, make change and save it back
Product p = new Product();
if(p.Load(productID))
{
    p.Name = "New Name";
    p.Save();
}

As you can see, our methods for fetching collections of objects/loading individual objects and saving changes are all built into the "Model" class. Each of our Model classes inherits from an ObjectBase base class which includes DB access functions and change tracking so when someone changes a value through a property the object is automatically marked dirty and notifications are fired to whatever object (UI) has subscribed to those events.

What I would like to do is use the "Repository pattern" so that we can abstract the Database implementation away from the Model. However, much of the code I have been looking at seems to suggest that the "Model" class should not contain any intelligence and should just be a container for data. Instead, the logic should be applied through the use of services. Does this then mean to accomplish the above I would need to do something like

List<Product> prods = ProductService.GetProducts();

Product p = ProductService.GetSingleProduct(productID);
p.Name = "New Name";

ProductService.SaveProduct(p);

This seems a more complex way of doing it and makes it harder to encapsulate functionality within business objects.

Can someone explain why this is a better way of doing it or maybe have I misunderstood the concepts?

Thanks

James

+2  A: 

I think the primary issue here is separation of concerns: why should your business object care how it is persisted? Why should your persistence layer care how your business objects are validated or enforce business logic? By separating the two you make a clean distinction between how your objects operate from a business perspective and how they are saved/retrieved from the database. As a result your business objects become much less complex (that's good) and you are able to take advantage of commonalities more easily in the persistence layer to reduce the amount of code needed.

One example of a situation in which this has really helped me is with subclassing of Model objects. When I was building the Save logic into the model, I would derive a fair amount of the logic from the BI base class and implementing a virtual method to do the actual save of the object in my Model class. This worked fine as long as my BI Model hierarchy was flat. It blew up when wanted to subclass a Model. At that point I had to reimplement a lot of the code for saving because I couldn't use the Base class code without also reusing the immediate parent's code -- which I couldn't do.

I've since moved to using LINQ as an ORM and now the save/retrieve logic is in the DataContext and the business logic is implemented in partial classes for each business entity. These classes implement validation (and other business logic) and load checking via a well-known interface. The interface is used by the DataContext to perform the operations that it needs to ensure that the business rules have been satisfied before persisting the object. Now my Model classes are much more single-purpose and easier to maintain. LINQ enforces some constraints on subclassing, but I can work around that by constructing interfaces or, if necessary, reworking my DB table to support their subclass constraints. All-in-all, I've found it to be a vast improvement.

tvanfosson
+3  A: 

Your current API is an implementation of the Active Record Pattern. This pattern tends to work fine when the object model used in the code is a one-on-one match with the database model. Another advantage is that tooling exists to generate these classes,including the persistence code, and database tables .

The alternative you suggest is the Repository Pattern. As you already mention implementing this is a bit more complex, but has several advantages. Since you can implement any kind ORM tool you're not limited to one-on-one mappings, but can implement more complex mappings where the object model can be different from the database model. So you don't have to force an object model in the database or the other way around. However the more complex mappings, other than one-on-one can't be generated and require some

Another advantage is that you can create tests more easily, because you can create a Mock repository that doesn't even require a database.

Using the Repository Pattern you also separate the model from the persistence logic.

In both situations it's possible to write the persistence methods in a generic fashions so that the persistence code is generic a doesn't need to know about a specific object that needs to be persisted. This is obvious for the Active Record Pattern since all these objects implement save, delete, update, etc.. For the the Repository Pattern you can also use ORM tools that work on any object so that code like this is possible:

Repository.Save(ObjectOfAnyType);

ObjectOfAnyType can be anything as long as the ORM tool has some mapping defined/implemented for the type of the object.

So you choose, do you want or need these advantages at the cost of a little added complexity. Or does the simplicity of the Active Record Pattern suffice.

I always tend to use the Repository Pattern, but have used the Active Record Pattern on occasion, mostly for quick prototyping.

Marco Tolk
A: 

@tvanfosson, @Marco Tolk Thanks for both your responses, very useful.

I really like the separation of concerns the repository pattern brings. It does add more dependencies between the objects but I suppose using something like StructureMap effectively removes that as an obstacle.

However, I still don't like the simplified 'Model' concept. Shouldn't the logic pertaining to a object (such as the "product" in the above example) be contained within the object itself?

For example, if I were binding my product object to an editor, I would want it to modify the properties of the object and then when the user hit save, have the product persist itself (perhaps via the repository). It doesn't make sense to me to have a service between the UI and the business object when the business object "knows" enough to persist itself without being piped though another service.

James