I have a block of code which is used multiple times in multiple class methods. I would like to make it into a separate function, but the code block in question is an if statement with a return, e.g.
private void method() {
//..
if (condition) {
//..
return;
}
//..
}
The problem is that if I pull this out into a separate function, the return applies only to that function itself, and no longer to the class methods in question. What is the best way to deal with this situation?
A good solution is to extract the condition code to a new method that returns a bool
and handle this in every method. The code might look a little like this:
private bool CheckCondition()
{
if (!condition) // Please recognize the NOT for this condition.
{
return true;
}
// .. your code from if statement
return false;
}
private void Method()
{
if (!this.CheckCondition())
{
return;
}
// ...
}
For completeness - there is another way but I would not recommend that:
private void WithCondition(Action action)
{
if (condition)
{
// ..
return;
}
action();
}
private void Method()
{
void Body()
{
// your old method body code after your condition here
}
this.WithCondition(Body);
}
But that looks weird. There are use cases for local functions like factory methods e.g. for non-blocking or some event handlers. But your case is not a common use case for that.