Assume I have a Query – as in CQS that is supposed to return a single value.
Let’s assume that the case that no value is found is not exceptional, so no exception will be thrown in this case. Instead, null
is returned.
However, if no value has been found, I need to act according to the reason why no value has been found.
Assuming that the Query knows the reason, how would I communicate it to the caller of the Query?
A simple solution would be not return the value directly but a container object that contains the value and the reason:
public class QueryResult
{
public TValue Value { get; private set; }
public TReason ReasonForNoValue { get; private set; }
}
But that feels clumsy, because if a value is found, ReasonForNoValue
makes no sense and if no value has been found, Value
makes no sense.
What other options do I have to communicate the reason? What do you think of one event per reason?
For reference: This is going to be implemented in C#.
9
Many internet protocols are built around a response code that is always returned along with an associated message. SMTP and HTTP being two well known examples.
Thus, public TReason ReasonForNoValue
becomes something more along the lines of public TResponse ResponseCode
The response could be an integer and follow the SMTP and HTTP style example, or it could be an enum for some type safety, or even a string (though this imposes some dangers of not doing string comparisons correctly somewhere, or a typo).
When there is an error (and indicated by the ResponseCode), the value could then hold more specific information (akin to a 404 page in HTTP).
I like the solution you propose. You may later wish to refactor ReasonForNoValue
into something more generic, but at least you have the structure to do so if necessary.
Advantages to your approach:
- It’s expandable if you ever need to return more data or metadata
- It separates the actual data from the metadata
- There are no
magic numbers
- It’s easy to parse.
Telastyn suggested another good approach – just return a single TValue
and support a new server call WhyWasThisNull()
First of all, I would most likely use an exception in this case. Catchy slogans aside, exceptions are the standard way to concisely specify a “success” control flow and an orthogonal “non-success” control flow. How commonly the non-success path happens has little to do with it, especially when you’re adding exception overhead to the much larger database query overhead.
My second choice would be having the calling class implement a result interface, something like this:
public class Caller implements ResultHandler {
public void findValue(Query query) {
query.execute(this);
}
public void valueFound(Value value) {
System.out.println("Found value " + value);
}
public void valueNotFound(String reason) {
System.err.println("Value not found: " + reason);
}
}
Like an exception, this solution has the benefit of being unignorable on null values. This architecture also makes it easy to do other things while you wait for the query to complete. Also, you should really be putting valueFound
and valueNotFound
in their own functions either way.
Your QueryResult
object is better than returning null
, but has the drawback of requiring boilerplate code everywhere to check the response code. If someone later on forgets that boilerplate, or intentionally omits it thinking the value will always be found, there’s no telling what state that will put the code into.
In other words, it adds burden on the maintainers. It may seem blatantly obvious that you need to check the response code now, but it won’t be so obvious two years from now. The more errors are caught by the compiler, the better.
What other options do I have to communicate the reason?
If your result is a string, you can have the reason be there with some signature that indicates it’s a bad result.
If your result is a number, you can have negative (or other bad values) be some error code.
You can have a separate query that users can call (if they so desire) to determine cause of null.
None of these seem clear cut better than your result/error object except perhaps the last depending on your usage.
What do you think of one event per reason?
I think that events are a largely terrible way to dispatch logic and a fairly rigid/coupled way of signaling a querying error which depends specifically on your data storage/format and would need to change if the query changes to cause different kinds of failure.
4
You could use your object and make something like:
public class QueryResult
{
public TValue Value { get; private set; }
public TQuerySuccess SuccesValue { get; private set; }
}
You read the succesvalue to see whether query was sucessful, if it was, value will contain queryresult, if it wasn’t value will contain failreason.
My suggestion is do one of this:
1. Use the QueryResult object but change the name of QueryResult.ReasonForNoValue() to QueryResult.Message().
public class QueryResult
{
public TValue Value { get; private set; }
public TMessage Message { get; private set; }
}
2. Rise KeyUnknowException or NoTranslationException, although you already said you don’t like this solution.
3. Always return a non-null value. Only that two special string values exist: “#UKNOWN_KEY” and “#NO_TRANSLATION”.
EDIT: (thanx to @DanielHilgarth) You would need to document several things:
- That a missing value doesn’t return
null
but still astring
. - That a missing value is indicated by several magic strings (with the same implications as magic constants).
- What each of those magic strings means.
And finally, someone would have to actually read that documentation.
In general, this kind of architecture increases the possibility of bugs.
4