Thursday, August 12, 2004

Brittle relations

Much of the time a project needs decoupling between a database schema and the business model using the schema. This setup uses some kind of mapping file, often XML, to glue the two pieces together. However as the schema evolves, mismatches between schema and business model show up at run-time during testing. This is very annoying. If a project does not need the looseness afforded by a separate mapping file, I have a different suggestion. The most common design in this scenario is to have a persistence layer for database work and a domain layer above that representing the business model.

Consider an intermediate third layer—call it the schema layer—between the persistence and domain layers. This schema layer uses the persistence layer to exactly model the database schema rather than the business model. The domain layer uses the schema layer rather than call the persistence layer directly.

Why the extra layer? With the extra schema layer the mapping file vanishes. Use tools to generate the schema layer automatically by interrogating the database during the build. Then, as the schema evolves, incompatible syntactic changes (changes in columns or types, not changes in meaning) propagate into the code of the schema layer and manifest themselves as compile errors in the domain layer. This is a great aid during development. Compile-time errors are much easier to catch automatically than problems during testing, and strange reflection contortions are kept out of the business model.

Post a Comment