Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a name for this "pattern"?

I'm wondering if there is a name for this "pattern" where a method signature is called TrySomething, e.g. int.TryParse, decimal.TryParse, etc.

A coworker of mine uses this naming convention frequently -- rather than returning a value or throwing an exception, they will call a method TryDoSomething and if an exception is caught during processing it gets returned via out param.

Edit: I understand the example privided is not how the TryParse methods work. That was the point of posting this... I wasn't sure what to call it. I agree it seems more like a naming convention and not a pattern. Thanks for all the input.

Edit: Interesting...

Consider the TryParse pattern for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions.

To implement The TryParse pattern, you provide two different methods for performing an operation that can throw exceptions in common scenarios. The first method, X, does the operation and throws the exception when appropriate. The second method, TryX, does not throw the exception, but instead returns a Boolean value indicating success or failure. Any data returned by a successful call to TryX is returned using an out (ByRef in Visual Basic) parameter. The Parse and TryParse methods are examples of this pattern.

like image 560
Dave Ziegler Avatar asked Mar 31 '11 19:03

Dave Ziegler


1 Answers

I would likely call that the Error Hiding Pattern. You benefit from creating a TryX when you have code that would usually produce an exception that instead cuts out early with a boolean. If you look at the methods provided by the framework you'll notice the TryX variants exist whenever it would be non-trivial or error-prone (or done so often it should be in the framework) to write your own IsValidX method.

If you have to catch an exception, there is no sense wrapping this in a method. All you are doing is making it harder to debug input problems. Instead of having a nice stack trace to follow to trace down an input failure, the user may only see side effects of the failed method. Worse still, when debugging the issue at hand the developer potentially has to recreate obtuse program state in order to effect the failure mode.

Basically, if a priori you know an operation will fail with an exception, it is logical and proper to provide a companion TryX operation. This is the so-called Tester-Doer pattern. Post hoc analysis of an operation is not Tester-Doer, but rather just simple Exception Handling.

like image 79
user7116 Avatar answered Sep 25 '22 09:09

user7116