I often find myself writing code that will return early if a condition occurs, but continues if that condition does not occur.
For example, in the below code, FooBar() gets a Result from Foo(). If it is not Result.Success, FooBar() should return that result immediately, and not process the object any further. Then, do the same for Bar().
enum Result
{
Success,
CriticalError,
MinorError,
}
Result FooBar(object someValue)
{
Result result = Foo(someValue);
if(result != Result.Success)
{
return result;
}
result = Bar(someValue);
if(result != Result.Success)
{
return result;
}
DoSomething(someValue);
return Result.Success;
}
It bothers me (slightly) that I have to set the variable, then have the if statement, other than simply returning the value if (and only if) it meets a condition.
Ideally, there would be something like this:
Foo(someValue).ReturnIf(result => result != Result.Success);
Aucun commentaire:
Enregistrer un commentaire