为了账号安全,请及时绑定邮箱和手机立即绑定

有没有好的方法来重构使用重复条件语句的方法?

有没有好的方法来重构使用重复条件语句的方法?

翻过高山走不出你 2023-12-13 16:55:37
我有两个类似的方法,具有重复的条件和重复的 else 块。我想重构它以共享相同的逻辑和 else 块,但调用不同的方法。我怎样才能做到这一点?public void entryPoint1(...){    if(nullCheckStuff) {}        method1(stuff);        method2(stuff);    } else {        //log error    }}public void entryPoint2(...){    if(nullCheckStuff) {        method2(stuff);    } else {        //log error    }}
查看完整描述

3 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

如果您使用 Java 8 或更高版本,一个可能的解决方案是使用 lambda。您可以使用通用逻辑定义内部函数,该函数采用 Runnable 作为参数:


private void commonLogic(Runnable action)

{

    if(nullCheckStuff) {

        action.run();

    } else {

        //log error

    }

}

那么你的原始函数看起来就像:


public void entryPoint1()

{

    commonLogic(() -> { method1(); method2()});

}


public void entryPoint2()

{

   commonLogic(() -> method2());

}

您可能还需要向commonLogic()函数添加更多参数以传递nullCheckStuff表达式和错误处理块所需的数据。


查看完整回答
反对 回复 2023-12-13
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

如果您的方法还没有太多参数,您可以这样重构:


public void commonEntryPoint(..., boolean m1Condition) {

    if(nullCheckStuff) {

        if (m1Condition) {

            method1(stuff);

        }

        method2(stuff);

    } else {

        //log error

    }

}

干杯!


查看完整回答
反对 回复 2023-12-13
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

所以你的代码是这样的:


public void entryPoint1(...)

    {

        if(nullCheckStuff) {}

            method1(stuff);

            method2(stuff);

        } else {

            //log error

        }

    }


public void entryPoint2(...)

    {

        if(nullCheckStuff) {

            method2(stuff);

        } else {

            //log error

        }

    }

您必须取出 if 块并将其放入另一个函数中,比方说checkNullStuff():


public bool checkNullStuff(<object, string, whatever> condition, int entrypoint) {

    bool everythingOk = true;

    //checks if null

    if(condition) {

      return !everythingOk;

     }

    //executes common methods

     method1(stuff);

    //if not empty check what to do


    switch(entrypoint) {

      case 1:

         method2(stuff);

        break;

      case 2:

        method3(stuff);

        break;

      default:


        everythingOk = false;

    }

    return everythingOk;

}

为什么我使用 switch 而不是 if,如果你的入口点增长并且需要执行更常见的方法和入口点函数:


public void entryPoint1(...)

{

    // here we check if went wrong, otherwise the functions were executed

    if(!checkNullStuff(nullCheckStuff, 1)) {}

       // code for when nullCheckStuff was not what we exepected

    } 

}


查看完整回答
反对 回复 2023-12-13
  • 3 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信