Code duplication issue inside an if

52 views Asked by At

I have a code duplication that I want to avoid but I cannot create a method containing the code because there is a slight difference in a line inside an if. Here's what I mean :

Code 1 :

If case1 ()
{
    same code
    if()
    {
        same code 
        line1
    }

Code 2 :

If case2 ()
{
    same code
    if()
    {
        same code 
        line2
    }

Both codes are the same except one line (line1 and line2). Since the code is big I want to be be able to copy it inside a function for example. Do you have an idea how to this?

Thanks

2

There are 2 answers

1
cedrou On

You could split your code into multiple methods:

if (case1)
{
    subMethod1();
    if ()
    {
        subMethod2();
        line1;
    }       
}

if (case2)
{
    subMethod1();
    if ()
    {
        subMethod2();
        line2;
    }       
}
3
nvoigt On

Generally speaking, you are looking for an Action or Func. That's a type that encapsulates executable code:

public int YourCommonMethod(int parameter, Func<int, int> calculate)
{
   // some common code

   if(calculationNeeded)
   {
      // some common code
      result = calculate(parameter);
   }

   // more common code
}

You could then call it with two different calculation methods:

int result = YourCommonMethod(5, i => i + 17);

OR

int result = YourCommonMethod(5, i => i / 48);

For just an action, you need less:

public int YourCommonMethod(int parameter, Action<int> doWork)
{
   // some common code

   if(calculationNeeded)
   {
      // some common code
      doWork(parameter);
   }

   // more common code
}

And you can call it like this:

int result = YourCommonMethod(5, Console.WriteLine);

OR

int result = YourCommonMethod(5, i => Console.WriteLine("Some string including {0}", i));