5

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#.

  • 1
    If your query result is null, what other reason besides 'not found' would you possibly expect? Put another way, what are all the possible values for ReasonForNoValue? If there's only one, then the presence of null would imply it. – Dan Pichelman Jun 25 '13 at 13:54
  • @DanPichelman: My concrete context is a translation service and the query takes a key and a target language as input and returns the translation as a result. There are at least two reasons why a translation can't be found: (1) The key is unknown. (2) The key is generally known, but there exists no translation for the specified target language. – Daniel Hilgarth Jun 25 '13 at 14:00
  • This is going to depend a lot on language I think, e.g. in ML family a sum type and pattern matching, but I suspect from your snippet that sum types aren't really doable for you – jk. Jun 25 '13 at 14:43
  • @jk.: I have never worked with ML. Could you explain shortly what that would do? – Daniel Hilgarth Jun 25 '13 at 15:08
14

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).

3

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()

1

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.

0

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.

  • I think that communicating the reason in the string or integer that is returned is the worst possible solution. On the other hand, I don't understand the reasons you bring forward against events. I don't see how the events depend on the "data storage/format" - the reason for a value that couldn't be found is not technical, it is logical, see the example in my comment to the question itself. – Daniel Hilgarth Jun 25 '13 at 14:32
  • @DanielHilgarth - that you have keys at all is an abstraction leakage that you're using a relational database. What happens if you move the translations into a NoSQL style document cache? Different reasons for the thing to not be found. (And yes, the string/int are horrible options, but they are options). – Telastyn Jun 25 '13 at 14:50
  • @Telastyn: I strongly disagree that key is a leakage of a relational database. In fact, the key has nothing to do with the persistance mechanism. In my specific case, it is the name of the UI control that should be translated. But actually it can be any string, i.e. a GUID. This would work with NoSQL, Cloud, XML... Basically, it is a simple key -> value mapping: (translation key, target language) -> text representing translation key in target language – Daniel Hilgarth Jun 25 '13 at 14:57
  • 1
    In a concurrent system it may not be possible to provide the cause of null later on, because the system state may already have changed. – SpaceTrucker Jun 26 '13 at 11:35
0

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.

0

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:

  1. That a missing value doesn't return null but still a string.
  2. That a missing value is indicated by several magic strings (with the same implications as magic constants).
  3. 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.

  • Option one is nothing I would ever consider. See the comments on Telastyn's answer as to why. – Daniel Hilgarth Jun 25 '13 at 14:58
  • @DanielHilgarth I read all the comments on Telastyn's answer. Some of them say returning the reason in the return value is "horrible" and the "worst solution", but explanation of why that is so. – Tulains Córdova Jun 25 '13 at 15:13
  • Because it is an implicit concept. The discoverability of the API is severly hurt. You would need to document several things: (1) That a missing value doesn't return null but still a string. (2) That a missing value is indicated by several magic strings (with the same implications as magic constants). (3) What each of those magic strings means. And finally, someone would have to actually read that documentation. In general, you increase the possibility of bugs with this kind of architecture. – Daniel Hilgarth Jun 25 '13 at 15:19
  • @DanielHilgarth You are right. I improved the answer. – Tulains Córdova Jun 25 '13 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.