This code has been bothering me all day, partially because the
if (result != OpResult.Success) { // return
code is repeated, everywhere.
A series (1..n
) of evaluation are performed. After each evaluation, a check is made to ensure that the operation was a success (utilizing a custom return value derived from an enumeration): OpResult.Success
.
Here is an example (with example objects, etc.):
OpResult result = OpResult.Sucess;
result = performOperationOne(commonObjectArgument);
if (result != OpResult.Success)
{
trace.Exit(); // Exit logging mechanism
return result;
}
result = performOperationTwo(commonObjectArgument);
if (result != OpResult.Success)
{
trace.Exit();
return result;
}
As you can see, if (result != OpResult.Success)
is used as flow control, i.e. unless all preceeding oprations are a success, then the next will not run.
With the .Net 4.*, C# has become capable of some pretty incredible things, syntactically. Is there anything that I can do to eliminate needing to re-write this evaluation after every operation?
One possibility is to build a list of operations and perform them in a loop:
var operations = new List<Func<CommonObjectArgumentType, OpResult>>
{
Operation1,
Operation2
};
OpResult result = OpResult.Success;
foreach (var op in operations)
{
result = op(commonObjectArgument);
if (result != OpResult.Success)
{
trace.exit();
return result;
}
}
// all operations were successful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With