Query something and return the reason if nothing has been found

Posted by Daniel Hilgarth on Programmers See other posts from Programmers or by Daniel Hilgarth
Published on 2013-06-25T13:52:25Z Indexed on 2013/06/25 16:28 UTC
Read the original article Hit count: 266

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

© Programmers or respective owner

Related posts about design-patterns

Related posts about architecture