Sunday, October 2, 2011

The Repository Pattern

I'm not sure if Martin Fowler conceptualized the repository pattern, but his book Patterns of Enterprise Application Architecture (PoEAA) is where I first came across the definition:

"Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."

He has very carefully selected his words. I have my own definition. Consider it the layman's version:

"Separates data from its source." 

Let's dig into an example.

The Repository Pattern in .NET

Every .NET programmer has written some sort of code that accesses a database or web service and returns something. Traditionally, the ever-present n-tier/three-tier philosophy dictates that the code for that should be in its own package/layer, the data access layer. What that philosophy does not dictate is the method signature and the return type; they're extremely important. Let's look at your traditional DAL:

What will the dev on this project do if the People DB gets outsourced and is now accessed via webservice? Convert the web service return into datasets, or change all the business layer classes to work with whatever the new return is? Or, what if they change to a db that doesnt easily convert into datasets? Not a great position to be in... Why not change it to something more generic that will never change?...

Here's a look at the repository pattern implementation:

Notice how this implementation could survive through any sort of data source change because it is using "a collection-like interface"? Much more maintainable.

The Repository Pattern in JavaScript

JavaScript's implementation would need to take into account the fact that AJAX requests (or all node.js functions) are meant to happen asynchronously. In order to allow for this, all we really need to do is implement the callback pattern, which really just boils down to passing an extra function.

That's it!

No comments:

Post a Comment