Tuesday, May 08, 2012

The object-relational mapping problem: my two cents

This is a big problem, nicely summarized by Martin Fowler in http://martinfowler.com/bliki/OrmHate.html.

In my view, the main issue is that we have different abstraction levels in memory and in the database. If you work with classes like Person and Flight and Passenger in memory, and you work with varchars and ints in the database, you are calling for trouble. If your business logic is simple, and your objects look more like data than like objects, these differences may be a minor issue, but an issue after all: you can write things like select * from PASSENGERS, FLIGHTS where PASSENGERS.DESTINY = FLIGHTS.DESTINY and PASSENGERS.AGE > 18, which is OK, but also things like select * from PASSENGERS, FLIGHTS where PASSENGERS.DESTINY = FLIGHTS.DESTINY and PASSENGERS.AGE > FLIGHTS.NUMBER which does not make sense, but it works because both are ints, and may return some data.

In a higher abstraction level, you could possibly want to write things like select * from PASSENGERS, BAGGAGE_PIECES where PASSENGERS.ID = BAGGAGE_PIECES.PASSID and PASSENGERS.AGE > BAGGAGE_PIECES.WEIGHT and be warned that you are trying to compare an Age and a Weight, and that it is not allowed. To achieve this, you need support for Abstract Data Types (ADTs) in your relational database, and current commercial and open source database managers provide this support. The relational model allows this, although some vendors prefer to call it object-relational. If you are thinking that storing ADTs would violate the first normal form in relational databases, you are missing the A in ADT.

Working at the highest possible abstraction level, and the one which is closest to your problem domain, is usually a good idea, specially if there are a number of developers involved and if you plan to create a maintainable application. Your relational database is a part of your application and, as long as you have the choice, you should aim at the highest possible abstraction level there too.

No comments: