简体   繁体   English

Java-重构几乎相同的方法

[英]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. 从2个地方调用此方法。 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() . 其次,我只想执行Code Block而不要执行CallToAnotherMethod()

How should I go about refactoring this? 我应该如何重构呢? Implementing 2 methods with 99% of the same code does not seem elegant. 用99%的相同代码实现2种方法似乎不太好。

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(...) . 要仅执行代码块,请调用methodForCodeBlock(...) To execute everything, call method(...) . 要执行所有操作,请调用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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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