Query Functions
Previously we learned about CQRS and how it promotes the separation of query and command functionality in our code. Today, we’ll take a closer look at query functions, or queries for short.
Examples of queries:
decimal Total => UnitPrice * Quantity; bool HasActiveOrders { get; } Customer[] SearchForCustomers(SearchCriteria criteria); IUser GetCurrentUser();
What do all these functions have in common? They’re all returning a value. They do not return void
. This is fair enough; when we query, we are asking for data. The caller can expect an answer. A function’s return value is the obvious way to communicate the query result back to the caller.
CQRS prescribes that queries don’t act like Commands and the other way around. In other words, when we perform a query, we shouldn’t change the state of the system. And this makes sense – imagine an app where requesting a customer’s open orders sets the order status to ‘Completed’! I think there would be a few unhappy customers and a heap of support tickets.
However, sometimes state changes must happen even for queries. I can imagine high-security systems where requests to classified or restricted information would be logged for auditing purposes. CQRS is a pattern that we can choose to adopt – or not.
Acceptable Return Values
What should a query function return when it cannot find the requested data? The answer depends on whether we are expecting a singleton or a collection.
In the case of the singleton, the caller of a query can expect to receive
- an instance of the single value or object, or
- a
null
value
The null
represents the query function returning empty-handed.
What about for a collection-type return value? For a collection, acceptable values are
- a collection of values or objects, or
- an empty collection
A null
, on the other hand, is not an acceptable return value for a collection-type. Responsible developers return empty collections, not nulls. Why? Nulls, instead of empty collections, are the cause of many dreaded C# NullReferenceException
s or Java NullPointerException
s.
Learn about Command Functions.
Leave a Reply
Want to join the discussion?Feel free to contribute!