Chapter 21. Embrace SQL Thinking
Dean Wampler
Look at this query:
SELECT c.id, c.name, c.address, o.items FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY c.id
We acquire all the customers who have orders, including their names and addresses, along with the details of their orders. Four lines of code. Anyone with a little SQL experience, including nonprogrammers, can understand this query.
Now think about a Java implementation. We might declare classes for Customer and Order. I remember well-meaning consultants saying we should also create classes to encapsulate collections of them, rather than use “naked” Java collections. We still need to query the database, so we pull in an object-relational mapper (ORM) tool and write code for that. Four lines of code quickly turn into dozens or even hundreds of lines. The few minutes it took to write and refine the SQL query stretch into hours or days of editing, writing unit tests, code reviews, and so on.
Can’t we just implement the whole solution with only the SQL query? Are we sure we can’t? Even if we really can’t, can we eliminate waste and write only what’s essential? Consider the qualities of the SQL query:
- We don’t need a new table for the join output, so we don’t create one.
- The biggest failing of applied object-oriented programming has been the belief that you should faithfully reproduce your domain model in code. ...