Whats the best practice for returning a Boolean and string value
I've created a method that performs some validations against an XML Hierarchy that is dynamically generated by another Class in Javascript text during run time.
My method currently returns either True or False, which is helpful for anyone using my Class but I'd like to also return more informative information since there may be several reasons that can throw a False messa开发者_如何学Pythonge.
At first I thought to change the return type from bool to some Generic Collection type having a String key and Boolean value I don't know if this is the best approach.
What is the Best Practice in this case?
Make a class like
public class ValidationResponse
{
public bool Successful { get; set; }
public string Information { get; set; }
}
and return object of ValidationResponse
One pattern, which is used in the TryParse
methods of .NET datatypes (e.g. Int32.TryParse), and is very common in the C world, is to return a boolean to signify success or failure. The user also has to pass in a value by reference to the method to receive the parsed value back.
For your circumstance, your method signature might look like:
bool DoSomething (out string anInformativeMessage)
HOWEVER I personally think the best approach is to return a Result
class Dhinesh has described in his answer, as it's more flexible, and OO in nature. I'm adding this approach for completeness ;)
Create your own results class, which your method returns and which contains all the information you need. With this, you can more easily extend it in the future (as in dhinesh's answer.)
Another option is to use a
Tuple
object to store both thestring
andbool
:Tuple<string, bool>
would be your return type. (Only available in .NET 4.0 onwards)
Creating a Result class as a new return type as suggested in other answers has the problem of breaking existing code.
If you want/need to avoid that, you could introduce a new string LastError
property containing error messages of the last call to your method, and keep the method signature intact. You'd use it like
bool success = myObject.MyMethod();
if(!success)
Console.Error.WriteLine(myObject.LastError);
This approach is not well suited for multi-threading environments.
The Rust std::result
type should also work similarly for C#:
enum Result<T, E> {
Ok(T),
Err(E),
}
You either:
- return an
Ok
type with the value - or an
Err
type with the error message
Old answer:
I don't know about best practice but if you only have the two following cases:
- Return true, with no extra information
- Return false, with extra information
Then you can simplify it down to just returning a string. If there is no error then you return an empty string which is the equivalent of an error code of zero.
string errorMsg = myObject.MyMethod();
if (errorMsg != String.Empty) {
Console.Error.WriteLine(errorMsg);
}
If it is expected that the XML Hierarchy will validate - Then I would say this is a typical example of where you should use an exception. The method then just returns void and throws on failure, like so:
void validateXMLHierarchy();
and to use
try
{
validateXMLHierarchy();
}
catch (XmlValidationException ex)
{
Console.Error.WriteLine(ex.Message);
}
精彩评论