Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY Fix Possibilities, C#

Tags:

c#

.net

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?

like image 583
Thomas Avatar asked Dec 07 '22 23:12

Thomas


1 Answers

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
like image 70
Jim Mischel Avatar answered Dec 27 '22 17:12

Jim Mischel