简体   繁体   中英

Java - Refactor almost identical methods

I have a method which looks something like this:

private void method(final Param one, final Param two) {
    Code Block
    CallToAnotherMethod() 
}

This method is called from 2 places. In one of the places, I want to call the entire method as is. In the second place, I want to only execute the Code Block but not the CallToAnotherMethod() .

How should I go about refactoring this? Implementing 2 methods with 99% of the same code does not seem elegant.

Thanks in advance for the suggestions.

Without any insight in the actual code, it is hard to judge it properly. As with any generic question, we can only provide a generic answer.

private void method(final Param one, final Param two) {
    methodForCodeBlock(one, two);
    callToAnotherMethod() 
}

private void methodForCodeBlock(final Param one, final Param two) {
    // code block here
}

private void callToAnotherMethod() {
    ...
}

To only execute the code block, call methodForCodeBlock(...) . To execute everything, call method(...) .

Here you have

private void method(final Param one, final Param two) {
    codeBlockMethod() 
    CallToAnotherMethod() 
}


private void method2(final Param one, final Param two) {
    CallToAnotherMethod() 
}

private void codeBlockMethod() {
    Code Block
}

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