开发者

How do i refactor this code by using Action<t> or Func<t> delegates

I have a sample program, which needs to execute 3 methods in a particular order. And after executing each method, should do error handling. Now i did this in a normal fashion, w/o using delegates like this.

class Program { public static void开发者_运维技巧 Main() {

        MyTest();
    }

    private static bool MyTest()
    {

        bool result = true;
        int m = 2;
        int temp = 0;

        try
        {
            temp = Function1(m);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function1" + e.Message);
            result = false;
        }

        try
        {
            Function2(temp);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function2" + e.Message);
            result = false;
        }

        try
        {
            Function3(temp);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for function3" + e.Message);
            result = false;
        }

        return result;
    }

    public static int Function1(int x)
    {
        Console.WriteLine("Sum is calculated");
        return x + x;
    }

    public static int Function2(int x)
    {
        Console.WriteLine("Difference is calculated ");
        return (x - x);
    }

    public static int Function3(int x)
    {
        return x * x;
    }
}

As you can see, this code looks ugly w/ so many try catch loops, which are all doing the same thing...so i decided that i can use delegates to refactor this code so that Try Catch can be all shoved into one method so that it looks neat. I was looking at some examples online and couldnt figure our if i shud use Action or Func delegates for this. Both look similar but im unable to get a clear idea how to implement this. Any help is gr8ly appreciated. I'm using .NET 4.0, so im allowed to use anonymous methods n lambda expressions also for this

Thanks


bool result = true;
int m = 2;
int temp = 0;

var funcs = new Func<int, int>[]{
                          x =>
                              {
                                  Console.WriteLine("Sum is calculated");
                                  return x + x;
                              },
                          x =>
                              {
                                  Console.WriteLine("Difference is calculated");
                                  return x - x;
                              },
                          x => x * x
                      };

temp = m;
foreach (var func in funcs)
{
    try
    {
        temp = func(m);
    }
    catch (Exception e)
    {
        Console.WriteLine("Caught exception:" + e.Message);
        result = false;
    }                
 }

Like another answer says, this can be overkill for this simple example. However it could still be useful in some cases, for example if you want to implement some retrying logic at each step (assuming you're doing something more complex than calculating values)


Thanks for the response...I was able to come up with this solution

@joel....thnx for the soln...as you can see, the excpetion thrown cant terminate the program....it shud continue after logging the exception.. here is my code I somehow still, feel that this can/shud be further refactored.!! i just donno how :(

any suggestions for further simplifying this..

Note: If a particular function throw an exception, the overall result shud be false...but shud continue executing other func's to see if any other func fails...

Also, the func's mentioned here are just for illustration, actual methods are more cmplx

class Program
{
    public static void Main()
    {
        ExecuteTask task1 = Function1;
        ExecuteTask task2 = Function2;
        ExecuteTask task3 = Function3;
        bool result = true;
        int param1 = 2, param2 = 3, param3 = 4;

        MyTest(task1, ref result, ref param1);
        MyTest(task2, ref result, ref param2);
        MyTest(task3, ref result, ref param3);

        Console.WriteLine("final result is " + result.ToString());
        Console.ReadLine();
    }

    private delegate void ExecuteTask(ref int x);

    private static void MyTest(ExecuteTask task, ref bool result1, ref int param1)
    {

        try
        {
            task(ref param1);
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught exception for " + e.Message);
            result1 = false;
        }

        return result1;
    }

    public static void Function1(ref int x)
    {
        Console.WriteLine("Sum is calculated");
        x = x + x;
    }

    public static void Function2(ref int x)
    {
        Console.WriteLine("Difference is calculated ");
        x = (2 * x - x);
    }

    public static void Function3(ref int x)
    {
        //Console.WriteLine("Product is calculated ");
        //x = x * x;
        throw new ArgumentOutOfRangeException();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜