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 anout
param, and returns abool
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;
}
}