c# - A design for a Foo/TryFoo method pair that has the best performance? -
i have common scenario of needing write pair of methods:
- one gets result , throws exception if fails, and
- a
try
-variant of same method attempts resultout
param, , returnsbool
indicates success status.
here 2 examples illustrate 2 approaches considering. of these approaches provides best performance? also, 1 approach easier maintain other? open suggestions other ways implement pair of methods.
method 1: foo()
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()
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; } }
the point of tryfoo()
api pattern avoid overhead of (potentially) throwing exception companion foo
function does.
your first example accomplishes this. note pattern in first example supported microsoft in reference source boolean.tryparse , boolean.parse.†
finally, note code analysis raise ca1021: avoid out parameters if include out
parameter in public method. question code analysis comes suggestion not using “out” parameters discusses warning. top-voted answer indicates tryparse
idiom well-established. therefore, making use of tryparse
approach in public api has chance of being well-received. so, reasonable (though subjective) argument can made in case suppress warning ca1021.
† links suggested damien_the_unbeliever
Comments
Post a Comment