Wednesday, July 22, 2009

N-Tier Design Revisit part 3 – Data Access Layer

The Data Access Layer abstracts your data requests away from the rest of your application and prevents your Biz Layer from needing to know where your data comes from.

In it’s simplest form a DAL is a class that pulls data from a data source(SqlServer, MySql, an XML File, a web service, the Cloud, etc.) populates a data entity and returns it to the Biz layer for some the DAL is simply a Object Relational Mapper like NHibernate or The Entity Framework, while this is fine, I would recommend against it for the simple reason that I want the Biz to know as little about where the data comes from as possible and if it’s talking directly to Entity Framework then it has more knowledge about how the system is setup then it should; and what happens if you have to change ORM Tools?  I think ORM tools are for the most part great, but I strongly feel you should abstract them away preferably using an interface this makes it much easier to swap of the underlying code if you have to, plus it makes it much easy to test. 

One type of ORM I would suggest you avoid are the code gen ORMs like subsonic, it’s quick and easy to pull your data entities, but your now very strongly tied to your database schema and database changes affect your entire application, also what if not all of your requests are to a database, at work we have several products that use 3rd party web services that tie into data from the database and are returned to the Biz Layer, that’s hard to do if your entities are being build for you by a code generator.   

Finally there are only 2 really solid rules for the DAL

1: Expose as little about your data sources as possible, this prevents them from being too tightly coupled to your data source.  Recently we switched data vendors for one of our products, as far as the rest of the application knew nothing had changed even though the underlying web service was completely different.

2: The only logic in the DAL is to filter data and map it to data entities, at this point all of your validation should be done (that’s the Biz layers job).

Technorati Tags: ,

No comments: