The following is C#, though the code pattern is probably relevant to any OO language.
I have two methods, MethodWithTry and MethodWithSomeReturnValue that I believe are functionally equivalent. I would like to know if one of them is the “correct” way. Is there something about one (ex. concurrency) that makes one of them a bad choice.
public void MethodWithTry()
{
int returnValue;
string someInput;
if (TryGetValueThisWay(someInput, returnValue))
{
//do something this way
}
else
{
if (TryGetValueThatWay(someInput, returnValue))
{
//do something that way
}
else
{
//do something a default way
}
}
}
public void MethodWithSomeReturnValue()
{
int? returnValue;
string someInput;
returnValue = GetValueThisWay(someInput);
if (returnValue != null)
{
//do something this way
}
else
{
returnValue = GetValueThatWay(someInput);
if (returnValue != null)
{
//do something that way
}
else
{
//do something a default way
}
}
}
The signatures for the methods being called are
public int? GetValueThisWay(string input)
public int? GetValueThatWay(string input)
private bool TryGetValueThisWay(string input, out int value)
private bool TryGetValueThatWay(string input, out int value)
EDIT — ADDITIONAL INFO
The methods in question being called are doing finds in collections. So different names might have been
public int? GetValueFromCollectionA()
public int? GetValueFromCollectionB()
IMHO, TrySomeMethodName – makes the code somewhat more readable.
However, using an OUT variable, especially when the return value is an integer, means that it is always mutable and assigned to at least twice (set to 0 as default).
If you operate on value types (like
int) and the result of your method can benull, you should go for theTryversion. This is because value types do not mix too well withnull. For exampleint?is way slower thanintbecause of boxing introduced by?. All .NETTryParsemethods work with value types and they follow this pattern. I think it’s good to conform to this approach.When you start to operate on reference types it becomes more natural to use method result and return
nullwhen needed.