Introduce Result Variable
- 2 minutes to read
In This Article
Introduces a variable to accept a value, replacing early-exit return statements with assignments to the variable and consolidating multiple method exit points into a single one.
#Purpose
This refactoring is great if you need to provide additional processing for your method’s return values. Instead of using values or calculated expressions in your return statements, the code works via a temporary variable, making it easier to implement value validation, for instance.
#Availability
Available from the context menu or via shortcuts:
- when the caret is on a return statement.
#Notes
- This refactoring first declares a variable of the same type as the method’s return type. Then it adds an assignment statement before each exit point so that return statements can return this variable’s value. Following that, if the code flow remains unchanged, return statements are eliminated.
- This refactoring is the functional opposite of Inline Result.
#Example
private string TestMethod(bool b)
{
if (b)│return "b - true";
else
return "b - false";
}
Private Function TestMethod(ByVal b As Boolean) As String
If (b) Then│Return "b - true"
Else
Return "b - false"
End If
End Function
Result:
private string TestMethod(bool b)
{
string │result;
if (b)
result = "b - true";
else
result = "b - false";
return result;
}
Private Function TestMethod(ByVal b As Boolean) As String
Dim │result As String
If (b) Then
result = "b - true"
Else
result = "b - false"
End If
Return result
End Function
#Animation
See Also