jargon

Design patterns·topic 6 of 10

Objects and the database between them

Objects have identity, references and behaviour; rows have keys, foreign keys and no behaviour at all. Every pattern here is a different position on how much of that gap to hide, and what each choice costs you later.

Read in order · tick what you already know

  1. 01

    inheritance, collections and object identity all had to become foreign keys, and none of the three translations were free.

    Object-relational impedance mismatch

  2. 02

    one method reads the rows, does all the logic and writes them back, and it is four hundred lines long.

    Transaction script

  3. 03

    one object holds every query for one table, and it returns rows rather than domain objects.

    Table data gateway

  4. 04

    each object is exactly one row, with a getter per column and nothing that knows anything about the business.

    Row data gateway

  5. 05

    the object has a save method on it, so the thing that models an order also knows the table it lives in.

    Active record

  6. 06

    the domain object has no idea a database exists, and a separate class knows which column each field came from.

    Data mapper

  7. 07

    you wrote no SQL, and then spent an afternoon reading the SQL it generated to find out why the page was slow.

    Object-relational mapping

  8. 08

    you changed four objects and called save once, and it worked out the order the writes had to happen in.

    Unit of work

  9. 09

    you loaded the same customer twice in one request and got the same object, not two equal ones.

    Identity map

  10. 10

    you looped over a hundred orders reading customer.name, and the log showed a hundred and one queries.

    Lazy loading

  11. 11

    you told the query to bring the customers along with the orders, and the hundred and one queries became one.

    Eager loading

  12. 12

    the code asks for the customer as if from an in-memory collection, and where it actually came from is somewhere else.

    Repository pattern

  13. 13

    there is one class per table with find, insert, update and delete on it, and the method names match the storage.

    Data access object

  14. 14

    the filter was built up as an object and handed to the repository, instead of being ten optional parameters.

    Query object

  15. 15

    one table holds three kinds of thing, a type column says which, and most columns are null for most rows.

    Single table inheritance

  16. 16

    the money object became two columns on the same row rather than a table of its own with a foreign key.

    Embedded value