Consider the following code:
// this method should add numbers, the requirements are:
// x >= 3 and y <= 5
int add(int x, int y)
{
if(x < 3) throw new ...;
if(y > 5) throw new ...;
}
It’s absolutely traditional approach, but in case you pass invalid values for both x and y, you’ll only get an exception for x. Why x and not y? Just because you first check x and only then y. Why? That’s basically the main question.
In the code above, there’s absolutely no sense in checking x before y or y before x. Just because the idea of execution flow in a single thread, some statements are executed before others.
I’m thinking about implementing a mechanism for working with parallel exceptions. The idea is, if there are 2 statements that can be executed simultaneously (execution order doesn’t matter) and both of them throw exceptions, I’d like to be able to handle all these exception. The pseudo-code is like following:
// this method should add numbers, the requirements are:
// x >= 3 and y <= 5
int add(int x, int y)
{
parallel
{
if(x < 3) throw new ...;
if(y > 5) throw new ...;
} // point A
return x + y;
}
Somewhere at point A the cumulative exception is thrown. Have you ever seen this approach before, or may be even implemented something of that kind? The main goal here is that if you have a complicated operation, that uses a number of another operation, and the “topmost” operation fails for some reason, you’re able to get full diagnostics for what was wrong: not a single error (or a number of nested errors), but a tree of errors.
The questions are:
- What do you think?
- Have you seen it before?
- Have you tried implementing something similar?
You seem to want to enforce a set of business rules.
One approach is to create a collection of broken rules and add specific broken rules (e.g. input too short, input must be alphanumeric) as separate elements of that collection, then throw a
BrokenRulesExceptionthat includes the collection of broken rules as a parameter.That allows the caller to fully understand what’s wrong with the input without changing any language semantics.