开发者

API Design: modify to return additional error information

开发者 https://www.devze.com 2022-12-15 01:55 出处:网络
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

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


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.


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


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.


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.


Just in case you wants to stick with option 3: validate() should not throw an exception in cases the validation fails because of wrong input. Exceptions should be thrown in exceptional cases and not in cases where you might expect wrong input. So I would design it in the following way

ValidationResult Validate()

where ValidationResult could be

class ValidationResult
{
   bool IsValid;
   string Message;
}

The validation method should only throw an exception when it is not able to validate, e.g. when it has to lookup values in a database but a connection could not be established.

EDIT: Wow. Didn't see the date of the post.... Guess I am a bit late...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号