dertoni
dertoni

Reputation: 1803

Pattern for returning specific error information or successful validation of an object

We have a combination of number where the first to numbers determine a format for the last one:

0001/0001/AF001 -> 0001/0001 == Rule for third number: two characters, three digits
0002/0001/0001 -> 0002/0001 == Rule for third number: four digits

We need to validate these numbers before storing them in a database. Since this is a common problem in several of our projects, we want to do the validation in a central service (in this case a ejb).

My first idea was to just use a method like:

public boolean isValid(String number1, String number2, String number3);

but we want to relay the rule if something is not valid, so that the user can see what went wrong, so my next idea is:

public void checkNumbers(String number1, String number2, String number3) throws DetailsException;

So one could invoke that like this:

try {
  checkNumbers("0001", "0001", "AF002");
} catch(DetailsException d) {
  // error handling
}

But this seems kind of ugly... What are the alternives/other ideas to solve this situation. Is there a typical pattern to use?

Upvotes: 0

Views: 246

Answers (1)

Vlad
Vlad

Reputation: 35594

Well, a customary (but somewhat old-fashioned) alternative to throwing an exception is returning an error code (or error object):

ErrorInfo err = checkNumbers(n1, n2, n3);
if (err != null)
{
    ...

But I personally would go for the variant with exception.

Upvotes: 2

Related Questions