Refactoring two methods with almost identical content

I have 2 methods that have almost the same content:

public string Method1(int someInt)
{
    if(someBoolean)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = getString(someInt)
    }
}

 public string Method2(myEnum myenum)
 {
    if(someBoolean)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = getString(myenum)
    }
 }

The differences are the method signatures and the only operator in else,string myStr = getString

Method 1 is called from many places, so it must remain somehow. How do I reorganize this?

+3
source share
6 answers

If your enum can be used in int, and if your getString returns the numeric value of the enum, not text, simply:

public string Method2(myEnum myenum) 
 { 
    return Method1((int)myenum);
 } 

How interesting aside - I saw that this situation came up with "the same gaps, different meanings."

Also as interesting aside - my head compiler says that the code does not actually compile :-)

- , , , , - , , .

:, enum getString , "Foo", , .

+5

:

public string Method<T>(T arg)
{
    if(someBoolen)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = getString(arg)
    }
}

, getString .

+5

Func

public string Method(Func<string> myFunc)
{
    if(someBoolen)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = myFunc();
    }
}

Method(myEnum => getString(myEnum));
Method(someInt => getString(someInt));

Generic - , getString, JSBangs.

+4

, ? , . :

1) , ?

2) , , ?

, , . - , .

+3

int ?

public string Method(myEnum myenum)
{
    return Method((int)myenum);
}

public string Method(int someInt) {
    if(someBoolen)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = getString(someInt)
    }
}
0

:

, int - - , . "" enum , int enum.

, , - : , intellisense , int :

public string Method1(myEnum myenum)
{
    if(someBoolen)
        return "test";

    if(someOtherBoolean)
    {
        return "dfjakdsad";
    }
    else
    {
        string myStr = getString(myenum)
    }
 }

public string Method1(int someInt)
{
    return Method1((myEnum) someInt);
}

Update: . When Adam asks, this decision really implies that you will always transmit intthat corresponds to your member enum. In my experience, this is common practice (if an enum only matches a subset of valid ints, then what value does the enum provide?) - but make sure that it matches your use case.

0
source

Source: https://habr.com/ru/post/1755340/


All Articles