tags:

views:

51

answers:

4

I have an API defined as follows

bool IsValid()

Now, I want to modify the API so that if the return value is false, then I need additional
information why the validation failed.
I'm looking for an elegant want to solve the problem... Here are the options I have

Option 1:
bool IsValid(ref string errorMessage)

errorMessage is updated only if the result is false

option 2:

class Result<T>
{
   bool Succeeded;
   T Argument;
}

Result<string> IsValid()

Option 3:

void Validate();
//throw an exception if it invalid, just return if succeeded.

I'm not comfortable with any of the options listed above. So, wondering if there is any graceful solution that I might not be aware of

regards G

+4  A: 

Are your possible error messages a fixed set? In that case, I would define them in an enumeration, then make a Validate() method that returns a value of the enum type. This has the added advantage that, if you need to show the message to the user, you can easily use localized messages.

Konamiman
Yea, that sounds better than what I had.
SapphireSun
A: 

If you were using a dynamically typed language you could do something like:

def IsValid():
   if condition:
       return (True, "")
   else:
       return (False, "error message")

However, I would really spring for the exception method. It's standard and can be handled at any level above the failing code.

SapphireSun
I would say that using exceptions in this case is overkill. Anyway it can be acceptable if a companion *TryValidate* method is provided, but then we are returning to the original problem.
Konamiman
+3  A: 

I'd go for

int IsValid();

string GetErrorString(int id);

or if you can, better yet:

ValidCode IsValid();

string GetErrorString(ValidCode code);

where ValidCode would be an enum

Jorge Córdoba
+1  A: 

If you must you could use "string isValid()" where the method would return null or empty string on success and some kind of an error message otherwise.

I would never do that personally though. Having APIs do more than one thing increases the complexity.

Mihail