简体   繁体   中英

How do I refactor a code well using Action?

I have a question regarding Action and refactoring. Following code is essentially what I am doing. I figured since there are repeated codes, I will try and create a method that holds the common activity and use Action for cleaner codes sake. (In the SomeSettingChangeIHaveToDoCommonlyBeforeFAR ) However, because those common codes are very small even in real code, I feel like the code is not that cleaner.

public void FindAndReplace1(bool isThisGood)
{
    ... some find and replace code ...
}

public void FindAndReplace2(int somePara)
{
    ... other find and replace code ...
}

public void SomeSettingChangeIHaveToDoCommonlyBeforeFindAndReplace(Action findAndReplace)
{
    ... change setting ...
    findAndReplace();
    ... change setting back ...
}

public void Main()
{
    if (conditionA)
        SomeSettingChangeIHaveToDoCommonlyBeforeFindAndReplace(FindAndReplace1(true));
    else
        SomeSettingChangeIHaveToDoCommonlyBeforeFindAndReplace(FindAndReplace2(1));
}

While it does shorten the code a bit, because the common code is not that long, the readability of code I feel dropped a bit. Also does not help that I have a long as sentence as my method name.

Is it still a good practice to use action for such a case?

Here's how I would write it.

private void FindAndReplace(bool condition)
{
    if (condition)
    {
        FindAndReplace1(true);
    }
    else
    {
        FindAndReplace2(1);
    }
}

public void Main()
{
    ChangeSetting();
    FindAndReplace(conditionA);
    ChangeSettingBack();        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM