Make your queries consistent

April 8, 2003 11:53 PM

Unless there is a very good reason for it not to, software should behave predictably. Predictable software is easier to test, predictable APIs are easier to interface with, predictable programs are easier to use.

One tenet of predictability is that when you make identical queries against identical sets of data, the results should also be identical. In queries that return multiple responses, this includes the order in which the data is returned.

For example (and this is what prompted the post), always put sufficient ORDER BY clauses in your SQL queries that the data is assured to come back in the same order every time. If the ordering turns out to be a performance problem, it's time to remove them. Until then, get into the habit of putting them there by default.

1 Comments

An alternative to using ORDER BY to get your test data coming back in an expected order is to be a bit more sophisticated with your unit tests.

Instead of coding your unit tests along the lines of "The first record we get back must be for $500.00, the second for $200.00 and the third for $300.00", you code more like "We get three records back. One must be for $500.00, one for $200.00 and one for $300.00". But it's a pain for several reasons: Java's idea of static typing; the functionally-complete-but-not-very-concise API for the standard collection classes are two; and of course the fact that sometimes a query returns a lot of data, and you only need to test the first couple of records.

I wrestled with this for a while and in the end I settled on a couple of ORDER BY clauses in the right places. A good side-effect of this is consistent (if arbitary) ordering of data in the UI.

Comments are no longer being accepted for this blog entry. If you really want to make your voice heard, you can always email me.

Previously: Mail.app problem solved?

Next: A good host is hard to find