Skip to Content
97 Things Every Java Programmer Should Know
book

97 Things Every Java Programmer Should Know

by Kevlin Henney, Trisha Gee
May 2020
Beginner
267 pages
7h 37m
English
O'Reilly Media, Inc.
Content preview from 97 Things Every Java Programmer Should Know

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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

97 Things Every Programmer Should Know

97 Things Every Programmer Should Know

Kevlin Henney
Java Coding Problems

Java Coding Problems

Anghel Leonard
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781491952689Errata Page