0

I have a function called myFunction1 whose definition is the following:

function myFunction1()
{
    if condition1 then
        doSomething1();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}

Now I want to write a second function myFunction2 which is almost identical to myFunction1 except for a single case, i.e.,

function myFunction2()
{
    if condition1 then
        doSomething4();
        myFunction2();
    else if condition2 then
        doSomething2();
        myFunction2();
    else if condition3 then
        doSomething3();
        myFunction2();
    else throw Exception; 
}

Note that it is only the first if which differs from myFuction1. How could I write myFuction2 so as to avoid duplicating code?

Sotiris Kal.
  • 68
  • 1
  • 6

3 Answers3

0

If it is easy to read and maintenance, have some duplicates is good!

Yu Jiaao
  • 4,444
  • 5
  • 44
  • 57
0

If it's a functional language then refactoring this is easy. Just take out the difference and pass it in as an argument:

function myGenericFunction1(theThingToDo)
{
    if condition1 then
        theThingToDo();
        myFunction1();
    else if condition2 then
        doSomething2();
        myFunction1();
    else if condition3 then
        doSomething3();
        myFunction1();
    else throw Exception;
}

Now you can either use it directly:

myGenericFunction1(doSomething1);
myGenericFunction1(doSomething4);

Or use it to create your two functions:

function myFunction1 () {
    myGenericFunction1(doSomething1);
}

function myFunction2 () {
    myGenericFunction1(doSomething4);
}

myFunction1();
myFunction2();
slebetman
  • 109,858
  • 19
  • 140
  • 171
0

If it's not a functional language, you can add a parameter to a single method:

function myFunction(case)
{
    if condition1 then
        if case == 1 then
          doSomething1();
        else
          doSomething4();
        myFunction(case);
    else if condition2 then
        doSomething2();
        myFunction(case);
    else if condition3 then
        doSomething3();
        myFunction(case);
    else throw Exception;
}

Or, depending on your actual case, it might make sense to pass doSomething1/4 as a function parameter, to avoid the if. That makes the code simpler when there are more possibilities.

Bartez
  • 172
  • 8