In some .NET libraries, there's a pattern of two alternative ways to call a function.
int i = x.GetValue(k); /* Might throw. */
if (x.TryGetValue(k, out int i) { /*...*/ } else { /* ... */ }
I don't like the names of these two functions as the not-Try variant presents itself the "normal" way to call a function. TryX, having the added word in the name, feels like a specialist form. For my new library that doesn't have to worry about existing users, I'd like to switch that around.
If I rename TryGetValue
to just GetValue
, what do I call the original GetValue
that will throw an exception if it can't complete my request?
Is there a standard name for this pattern? (I'm hoping the industry has an established pattern rather than coining a new word in the comments, but you're welcome to do so if you wish.)
EDIT: I could be persuaded that TryGetValue is the correct name, but I'd still like to change the name of GetValue that throws an exception, leaving no function called just GetValue.
1 Answer 1
The TryX
is a C# convention to indicate that the caller must check for errors explicitly and manually: failure is to be expected as part of normal program execution, so there won't be an exception.
Eliding this prefix is likely to lead to buggy code. Don't try to save these three characters, just stick to the convention.
In other languages, the compiler can enforce that the return value is checked, e.g. via [[nodiscard]]
in C++ or #[must_use]
in Rust. C# has no comparable feature.
-
I could be persuaded that TryGetValue is correct, but is GetValue the best name for the other varient?billpg– billpg2020年03月27日 13:57:09 +00:00Commented Mar 27, 2020 at 13:57
-
@billpg: I'm inclined to agree with Graham. There's no established convention like
GetValueAndThrowIfInvalid
. Feel free to create your own convention.Robert Harvey– Robert Harvey2020年03月27日 14:09:29 +00:00Commented Mar 27, 2020 at 14:09 -
2@billpg You don't have to create a throwing or non-throwing variant – that depends entirely on how these functions are supposed to be used. But if you want to steer users towards the non-throwing version, picking a longer name for the throwing version would be desirable. I'd consider
GetValueOrThrow()
.amon– amon2020年03月27日 14:12:13 +00:00Commented Mar 27, 2020 at 14:12
Explore related questions
See similar questions with these tags.
GetValue()
method to explicitly call out the exception that might be thrown.