Robin B. Robin B. - 1 month ago 11
C# Question

A design for a Foo/TryFoo method pair that has the best performance?

I have the common scenario of needing to write a pair of methods:


  • One that gets a result and throws an exception if it fails, and

  • a
    Try
    -variant of the same method that attempts to get the result as an
    out
    param, and returns a
    bool
    that indicates success status.



Here are two examples that illustrate the two approaches that I am considering. Which of these approaches provides the best performance? Also, is one approach likely to be easier to maintain than the other? I am also open to suggestions for other ways to implement this pair of methods.

Method 1:
Foo()
as master

public string GetAnswer(string question) {

string answer = null;

if(!this.TryGetAnswer(question, out answer)) {
throw new AnswerNotFoundException();
}

return answer;
}

public bool TryGetAnswer(string question, out string answer) {

answer = null;

//business logic

return answer != null;
}


Method 2:
TryFoo()
as master

public string GetAnswer(string question) {

//business logic

if(!answerFound) {
throw new AnswerNotFoundException();
}
return answer;
}

public bool TryGetAnswer(string question, out string answer) {

try {
answer = this.GetAnswer(question);
return true;
} catch (AnswerNotFoundException e) {
answer = null;
return false;
}
}

Answer

The point of the TryFoo() API pattern is to avoid the overhead of (potentially) throwing an exception that the companion Foo function does.

Your first example accomplishes this. Also note that the pattern in your first example is supported by Microsoft itself in its reference source for Boolean.TryParse and Boolean.Parse.

Finally, note that Code Analysis will raise CA1021: Avoid out parameters if you include an out parameter in a public method. The question Code analysis comes back with suggestion about not using “out” parameters discusses this warning. The top-voted answer indicates that the TryParse idiom is well-established. Therefore, making use of the TryParse approach in a public API has a good chance of being well-received. So, a reasonable (though subjective) argument can made in this case to suppress warning CA1021.


† Links suggested by Damien_The_Unbeliever