Simon Willison’s Weblog

Object relational mappings are over-rated...

... At least according to Tim Bray:

Lots of architects have learned, painfully, that you usually can’t magick relational rows away behind object/class abstractions. The right way to think about a database is as a set of normalized tables that are designed to be addressed with SQL strings.

This brings in to focus something I’ve been thinking about for quite a while. I always try to abstract away the details of the data storage layer behind some kind of interface, so that none of my front end code ever has to make a direct database call, instead calling methods on my application objects with names like “get_user_by_id” or “get_blog_entries_for_date”. The idea is that I could, if I wanted to, completely switch out the underlying data source. I should also be able to write new front-end functionality that calls the existing application layer methods without having to change anything in the data access code.

There are a couple of problems here. Firstly, I’ve already got a data abstraction layer in the form of SQL. Although there are many discrepancies between implementations, basic SQL statements such as selects and joins should work on pretty much any database. Additionally, in my three years of building web applications I can’t think of a single time I’ve needed to change the data layer for an existing application.

Modern database features such as stored procedures and constraints allow you to move huge chunks of application logic that relates to data coherency in to the database itself. In fact, PostgreSQL even allows you to write stored procedures in third party languages such as Python or Perl. With carefully written stored procedures, much of the important application logic could live in the database along with the data itself—a concept comparable to object oriented programming where the data and the methods that can be run on the data are encapsulated together.

I certainly haven’t made up my mind one way or the other, and at the end of the day the best approach is the one that gets a project completed in a reasonable time frame and that results in easily maintainable code. Plenty of food for thought, in any case.

This is Object relational mappings are over-rated... by Simon Willison, posted on 1st January 2004.

Next: Targets for 2004

Previous: Happy New Year!

Previously hosted at