In C#, I have a method that does a bunch of tests on a value. If the value fails any tests, it must skip the rest of them (some of them have side-effects).
Consider:
public void MyMethod(string myValue)
{
// Test A
if(myValue != myOtherValue)
return;
// Test B
if(myValue != someOtherValue)
return;
DoImportantThings();
}
This works, because if the value fails Test A, the method exits, and if never gets to Test B. It will only DoImportantThings()
if all tests pass.
But what if, when failing a test, I have to do one thing, always?
public void MyMethod(string myValue)
{
// Test A
if(myValue != myOtherValue)
{
DoMyOneThing();
return;
}
// Test B
if(myValue != someOtherValue)
{
DoMyOneThing();
return;
}
DoImportantThings();
}
This does work, but I hate the duplication. I'm paranoid that someone will add another test in the future and not include DoMyOneThing()
.
Here's what I would love:
[AlwaysDoBeforeExiting(DoMyOneThing())]
public void MyMethod(string myValue)
But, I know this isn't possible.
So, DoMyOneThing()
has to either be (1) before each return
, or (2) at the bottom of the method, in which case I can't return
from the method and instead need to find a way to short-circuit Test B (and all tests following) in the event that Test A fails.
What is the clearest way to write this code? Clearly, I can brute force this, but I'm curious if there's an elegant way to write it.
Is there an accepted/conventional way to abort the rest of a method while always ensuring some code runs? Is it -- gulp -- a try...catch...finally
block?