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

我有两个类似的方法,具有重复的条件和重复的 else 块。我想重构它以共享相同的逻辑和 else 块,但调用不同的方法。我怎样才能做到这一点?


public void entryPoint1(...)

{

    if(nullCheckStuff) {}

        method1(stuff);

        method2(stuff);

    } else {

        //log error

    }

}


public void entryPoint2(...)

{

    if(nullCheckStuff) {

        method2(stuff);

    } else {

        //log error

    }

}


翻过高山走不出你
浏览 151回答 3
3回答

大话西游666

如果您使用 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表达式和错误处理块所需的数据。

慕哥6287543

如果您的方法还没有太多参数,您可以这样重构:public void commonEntryPoint(..., boolean m1Condition) {    if(nullCheckStuff) {        if (m1Condition) {            method1(stuff);        }        method2(stuff);    } else {        //log error    }}干杯!

回首忆惘然

所以你的代码是这样的:public void entryPoint1(...)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(nullCheckStuff) {}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method1(stuff);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method2(stuff);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //log error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }public void entryPoint2(...)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(nullCheckStuff) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method2(stuff);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //log error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }您必须取出 if 块并将其放入另一个函数中,比方说checkNullStuff():public bool checkNullStuff(<object, string, whatever> condition, int entrypoint) {&nbsp; &nbsp; bool everythingOk = true;&nbsp; &nbsp; //checks if null&nbsp; &nbsp; if(condition) {&nbsp; &nbsp; &nbsp; return !everythingOk;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; //executes common methods&nbsp; &nbsp; &nbsp;method1(stuff);&nbsp; &nbsp; //if not empty check what to do&nbsp; &nbsp; switch(entrypoint) {&nbsp; &nbsp; &nbsp; case 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;method2(stuff);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; case 2:&nbsp; &nbsp; &nbsp; &nbsp; method3(stuff);&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; everythingOk = false;&nbsp; &nbsp; }&nbsp; &nbsp; return everythingOk;}为什么我使用 switch 而不是 if,如果你的入口点增长并且需要执行更常见的方法和入口点函数:public void entryPoint1(...){&nbsp; &nbsp; // here we check if went wrong, otherwise the functions were executed&nbsp; &nbsp; if(!checkNullStuff(nullCheckStuff, 1)) {}&nbsp; &nbsp; &nbsp; &nbsp;// code for when nullCheckStuff was not what we exepected&nbsp; &nbsp; }&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java